Menu

knownConditionTrueFalse false positive

2020-11-20
2020-11-22
  • Cameron Watt

    Cameron Watt - 2020-11-20

    Hi,

    When analysing some code with cppcheck 2.2 I seem to have found a false positive. It looks like cppcheck does not recognise that the pointer is incremented and so a subsequent check is not the same as a previous one.

    The following code shows that the increment actually occurs, the second conditional check of if (*ptr >= max_value) is not the same as the first one.

    Any advice would be appreciated.

    #include <stdio.h>
    #include <stdbool.h>
    
    bool inc_ptr_test(int max_value, int *ptr)
    {
        if (*ptr >= max_value)
        {
            printf("Returning after initial *ptr >= max_value check\n");
    
            return false;
        }
    
        *ptr = *ptr + 1;
    
        if (*ptr >= max_value)
        {
            printf("Taken 'if' branch, *ptr==%d, max_value==%d\n", *ptr, max_value);
    
            return false;
        }
        else
        {
            printf("Taken 'else' branch, *ptr==%d, max_value==%d\n", *ptr, max_value);
    
            return true;
        }
    }
    
    int cnt = 0;
    int *foo = &cnt;
    
    int main(void)
    {
    
        while(inc_ptr_test(10, &cnt));
    
    
        printf("main() : pre increment cnt==%d\n", cnt);
    
        *foo = *foo + 1;
    
        printf("main() : post increment cnt==%d\n", cnt);
    
        return 0;
    }
    
     
    • Cameron Watt

      Cameron Watt - 2020-11-20

      I should have added the output of the test, this is shown below...

      $ /home/cameron/Desktop/testcase/build/cppcheck_testcase
      Taken 'else' branch, *ptr==1, max_value==10
      Taken 'else' branch, *ptr==2, max_value==10
      Taken 'else' branch, *ptr==3, max_value==10
      Taken 'else' branch, *ptr==4, max_value==10
      Taken 'else' branch, *ptr==5, max_value==10
      Taken 'else' branch, *ptr==6, max_value==10
      Taken 'else' branch, *ptr==7, max_value==10
      Taken 'else' branch, *ptr==8, max_value==10
      Taken 'else' branch, *ptr==9, max_value==10
      Taken 'if' branch, *ptr==10, max_value==10
      main() : pre increment cnt==10
      main() : post increment cnt==11
      
       
  • Daniel Marjamäki

     

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.