Menu

false-positive: negativeIndex with multiple layers of function calls, arrays and ternary operators

Jens
2020-11-24
2020-11-26
  • Jens

    Jens - 2020-11-24

    I already mentioned this false positive in the IRC, but I dropped out, so I do not know if there were any responses, because I can't see the history.

    #include <stdio.h>
    #include <stdlib.h>
    
    #define maxIndex 4
    #define answerToAll 42
    
    int array[maxIndex];
    int otherArray[1] = {answerToAll};
    int otherArgument = 0;
    
    int func(int val) {
      return 0;
    }
    
    int main(int argc, char **argv) {
      int index;
      if (scanf("index %3i %3i",&index, &otherArgument)==2) 
        if(index<0 || index>maxIndex) { printf("err\n"); exit(1); }
        else {
          printf("%d\n", (otherArgument <= 0) ? -1 : otherArray[func(index ? array[index - 1] : 0)]);
        }
    
      return 0;
    }
    

    cppcheck (version 1.90) output:

    > cppcheck --enable=all .
    Checking test.c ...
    test.c:20:79: warning: Either the condition 'index<0' is redundant or the array 'array[4]' is accessed at index -1, which is out of bounds. [negativeIndex]
          printf("%d\n", (otherArgument <= 0) ? -1 : otherArray[func(index ? array[index - 1] : 0)]);
                                                                                  ^
    test.c:18:13: note: Assuming that condition 'index<0' is not redundant
        if(index<0 || index>maxIndex) { printf("err\n"); exit(1); }
                ^
    test.c:20:79: note: Negative array index
          printf("%d\n", (otherArgument <= 0) ? -1 : otherArray[func(index ? array[index - 1] : 0)]);
                                                                                  ^
    nofile:0:0: information: Cppcheck cannot find all the include files (use --check-config for details) [missingIncludeSystem]
    
     

    Last edit: Jens 2020-11-24
  • Daniel Marjamäki

    I believe this is fixed. I can reproduce the warning with cppcheck-1.90 but latest cppcheck is silent.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.