Vitor
Vitor

Reputation: 163

cppcheck dereference null pointer

I know cppcheck can check dereferencing of null pointers on variables. For example, this would trigger cpp check:

int* a = NULL;
*a = 5;

Is it possible to configure cppcheck so that it verifies also pointers returned by functions? Something like this:

int* foo() { return NULL; }
void main()
{
  int a = *foo();
}

And, if that is possible, would it also work on smart pointers?

Upvotes: 1

Views: 1244

Answers (1)

orbitcowboy
orbitcowboy

Reputation: 1538

Running your example with the latest revision of Cppcheck (https://github.com/danmar/cppcheck/commit/e6d692d9605850cf98153a4825e353898b9320a2) gives

$ g++ -c nullPointer.cpp && cppcheck --enable=all --inconclusive nullPointer.cpp
Checking nullPointer.cpp ...
nullPointer.cpp:4:14: error: Null pointer dereference: foo() [nullPointer]
 int a = *foo();
             ^
nullPointer.cpp:2:0: style: The function 'f' is never used. [unusedFunction]

$ more nullPointer.cpp
int * foo(void) {return 0;}
int f(void)
{
    int a = *foo();
    return a;
}

What version are you using?

Update: A test has been added meanwhile to Cppchecks unit testsuite: https://github.com/danmar/cppcheck/commit/fd900ab8b249eec37df706f338c227f2a9adb3ef

Update 2: Regarding smart pointers: Some issues with smart pointers are found. For example for this C++ code:

#include <memory>
int main()
{
    std::shared_ptr<int> p(nullptr);
    int a = *p;
    return a;
}

Cppcheck issues an error message:

./cppcheck fn_nullptr.cpp
Checking fn_nullptr.cpp ...
fn_nullptr.cpp:5:14: error: Null pointer dereference: p [nullPointer]
    int a = *p;
             ^
fn_nullptr.cpp:4:28: note: Assignment 'p(nullptr)', assigned value is 0
    std::shared_ptr<int> p(nullptr);
                           ^
fn_nullptr.cpp:5:14: note: Null pointer dereference
    int a = *p;
             ^

But returning a null-pointer via a smart pointer currently produces no error message. There is now a ticket requesting this: https://trac.cppcheck.net/ticket/9496

Upvotes: 2

Related Questions