Menu

Cppcheck checks on 'illegal values'

2015-02-12
2015-08-08
  • Wilson Snyder

    Wilson Snyder - 2015-02-19

    Thanks for the great work on cppcheck. I recently updated from 1.52 to 1.67, and happly fixed many reasonable new warnings. Two however I would like to improve.

    Consider this misuse of a dangling pointer:

     myDelete (ptr);
     badCode = *ptr;  // Uses dangling ptr
    

    Of course this will make code that may misbehave in strange ways. Therefore the convention in my program is that after a pointer is made invalid by e.g. deletion it is set to NULL so that the now-dangling pointer may not be misused. For example

     myDelete (ptr);      ptr=NULL;
     badCode = *ptr;  // Uses dangling ptr
    

    The point of this convention is that "badCode" will cause a core dump, which is obvious, instead of reading a stale value in the earlier example that did not set ptr to NULL. With cppcheck this style causes two warnings:

     func() {
        myDelete (ptr);   ptr=NULL;
     }
    

    This correctly gives a uselessAssignmentPtrArg.

     myDelete (ptr);      ptr=NULL;
     ptr = myNew();
    

    This correctly gives a redundantAssignment.

    The first question is can this coding convention be modified so that the warnings do not occur (I don't want to add suppressions as there are a lot of them, and generally perfer to fix warnings by coding convention.

    So, perhaps I should do this:

    #ifdef CPPCHECK
    # define INVALIDATE(p)  do { } while(0)
    #else
    # define INVALIDATE(p)  do { (p) = NULL; } while(0)
    #endif
    
    myDelete (ptr); INVALIDATE(ptr);
    

    Then for cppcheck runs, since INVALIDATE is a NOP, the warnings go away?

    What I propose would be ideal is when running cppcheck to define INVALIDATE to set ptr to some magic value, such that if ptr is later used then cppcheck will fire an error. For example:

    #ifdef CPPCHECK
    # define INVALIDATE(p)  do { (p) = __builtin_cppcheck_invalid(); } while(0)
    #else
    # define INVALIDATE(p)  do { (p) = NULL; } while(0)
    #endif
    
    myDelete (ptr); INVALIDATE(ptr);
    badCode = *ptr;   // cppcheck knows ptr is invalid so will throw an error
    
    ...
    
    myDelete (ptr); INVALIDATE(ptr);
    ptr = myNew();  // ptr no longer invalid
    

    Is there any such magic possible now? Might an enhancement like this be possible?

    Thanks!

     
  • Daniel Marjamäki

    See also:
    http://trac.cppcheck.net/ticket/4269

    how do we fix the false positives? I would like a reasonable solution.

    when it comes to pointers.. when can we safely warn and when can there be FP?

     

    Last edit: Daniel Marjamäki 2015-02-25
  • Daniel Marjamäki

    Also.. I had the feeling that we've made some fix for this in the past.

     

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.