Menu

False positive report

Michael T
2020-01-27
2020-02-03
  • Michael T

    Michael T - 2020-01-27

    Hi, I'd like to report two false positives in cppcheck 1.90

    Here's some code that reproduces them:

    #include <stdio.h>
    #include <stdlib.h>
    
    void Q_onAssert() __attribute__ ((noreturn));
    
    #define Q_ASSERT(test_) ((test_) ? (void)0 : Q_onAssert() )
    
    void Q_onAssert() {
        abort();
    }
    
    typedef void (*VoidFunc)(void);
    
    void sayHello()
    {
        printf("Hello World\n");
    }
    
    static VoidFunc getEventHandler()
    {
        return sayHello;
    }
    
    void indirectHello()
    {
        VoidFunc handler = getEventHandler();
        Q_ASSERT(handler != NULL);
        handler();
    }
    
    int main()
    {
        indirectHello();
        return 0;
    }
    

    The code compiles and runs in C, like so:

    $ gcc temp.c; ./a.out
    Hello World
    

    But checking with cppcheck produces this output:

    $ cppcheck-1.90/cppcheck --enable=all temp.c
    Checking temp.c ...
    temp.c:28:5: warning: Either the condition 'handler!=NULL' is redundant or there is possible null pointer dereference: handler. [nullPointerRedundantCheck]
        handler();
        ^
    temp.c:27:5: note: Assuming that condition 'handler!=NULL' is not redundant
        Q_ASSERT(handler != NULL);
        ^
    temp.c:26:39: note: Assignment 'handler=getEventHandler()', assigned value is 0
        VoidFunc handler = getEventHandler();
                                          ^
    temp.c:28:5: note: Null pointer dereference
        handler();
        ^
    temp.c:14:0: style: The function 'sayHello' is never used. [unusedFunction]
    
    ^
    nofile:0:0: information: Cppcheck cannot find all the include files (use --check-config for details) [missingIncludeSystem]
    

    Issue 1: The nonreturn on the Q_ASSERT isn't detected properly. Converting the Q_ASSERT macro to use if/else instead of an inline conditional makes this issue go away.

    Issue 2: sayHello is wrongly marked as never used. As you can see from the output when the code is run, sayHello does get used!

    Thanks for taking the time to read this bug report!

     
  • versat

    versat - 2020-02-03

    Thank you for the detailed bug report.
    I can reproduce the issues so I have created a ticket with your bug report: https://trac.cppcheck.net/ticket/9602

     

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.