Menu

False positive NULL pointer dereferece inside sizeof()

2022-09-16
2022-09-17
  • David Gibson

    David Gibson - 2022-09-16

    sizeof(*foo) doesn't actually dereference foo, and so shouldn't generate a NULL pointer dereference warning. However, cppcheck will do so under at least some circumstances. For example:

    #include <stdio.h>
    
    struct foo {
        int a;
        char b;
    };
    
    static void func(struct foo *foo)
    {
        size_t len = sizeof(*foo);
        printf("%zd\n", len);
    }
    
    void func2(void)
    {
        func(NULL);
    }
    
    $ cppcheck ~/tmp/foo.c 
    Checking /home/dwg/tmp/foo.c ...
    /home/dwg/tmp/foo.c:10:23: error: Null pointer dereference: foo [ctunullpointer]
     size_t len = sizeof(*foo);
                          ^
    /home/dwg/tmp/foo.c:16:6: note: Calling function func, 1st argument is null
     func(NULL);
         ^
    /home/dwg/tmp/foo.c:10:23: note: Dereferencing argument foo that is null
     size_t len = sizeof(*foo);
                          ^
    
     
  • CHR

    CHR - 2022-09-16

    Thanks for reporting, fixed by https://github.com/danmar/cppcheck/pull/4471

     
  • David Gibson

    David Gibson - 2022-09-17

    Wow, that was fast. Thanks!

     
    👍
    1

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.