Menu

incorrect "null pointer dereference" reports

2021-06-28
2021-06-29
  • Paul Aitken

    Paul Aitken - 2021-06-28

    Cppcheck reports "Null pointer dereference" in the following code:

    static void ptr_set(void) {
        void *ptr = somefn();
        if (!ptr) {
            if (whatever())
                goto done;
    
            ptr = anotherfn();
            if (!ptr)
                return;
        }
    
        if (ptr->member)
            return;
    
    done:
    }
    
    $ cppcheck --enable=warning /tmp/4.c
    Checking /tmp/4.c ...
    /tmp/4.c:12:6: warning: Either the condition '!ptr' is redundant or there is possible null pointer dereference: ptr. [nullPointerRedundantCheck]
     if (ptr->member)
         ^
    /tmp/4.c:3:6: note: Assuming that condition '!ptr' is not redundant
     if (!ptr) {
         ^
    /tmp/4.c:12:6: note: Null pointer dereference
     if (ptr->member)
    

    This is not reported if the "goto done" is replaced with "return". (In reality this is not possible because more code appears after "done:").

    Also, if the "if (whatever())" test is removed and only the "goto done" or "return" are left, then "Null pointer dereference" is always reported:

    static void ptr_set(void) {
        void *ptr = somefn();
        if (!ptr) {
            return;
    
            ptr = anotherfn();
            if (!ptr)
                return;
        }
    
        if (ptr->member)
            return;
    }
    
    $ cppcheck --enable=warning /tmp/4.c
    Checking /tmp/4.c ...
    /tmp/4.c:11:6: warning: Either the condition '!ptr' is redundant or there is possible null pointer dereference: ptr. [nullPointerRedundantCheck]
     if (ptr->member)
         ^
    /tmp/4.c:3:6: note: Assuming that condition '!ptr' is not redundant
     if (!ptr) {
         ^
    /tmp/4.c:11:6: note: Null pointer dereference
     if (ptr->member)
         ^
    

    "Null pointer dereference" is not reported once the unreachable code is removed, except for this pathological example:

    static void ptr_set(void) {
        void *ptr = somefn();
        if (!ptr) {
            if (!ptr)
                return;
        }
    
        if (ptr->member)
            return;
    }
    
     
  • 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.