Menu

nullPointer false positive with conditional operator

2026-01-08
2026-01-08
  • Frank Winklmeier

    Not sure if this is tracked already somewhere:

    struct Foo {
      void bar() {}
    };
    
    int main() {
      bool b = true;
      Foo* f = b ? new Foo() : nullptr;
      if (b) f->bar();
    }
    
    > cppcheck --version
    Cppcheck 2.19.0
    > cppcheck test.cxx        
    Checking test.cxx ...
    test.cxx:8:10: warning: Possible null pointer dereference: f [nullPointer]
      if (b) f->bar();
             ^
    test.cxx:7:14: note: Assignment 'f=b?new Foo():nullptr', assigned value is 0
      Foo* f = b ? new Foo() : nullptr;
                 ^
    test.cxx:8:10: note: Null pointer dereference
      if (b) f->bar();
             ^
    

    Replacing the conditional operator with a regular if-statement doesn't show this problem.

     
  • CHR

    CHR - 2026-01-08

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/14369

     

Log in to post a comment.