From 1ae24066feb92337e775b0ae2d5a624df8f24f1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 10 May 2009 08:43:16 +0200 Subject: [PATCH] null pointer dereferencing: check that its a pointer that is dereferenced to avoid false positives when using classes that behave almost like pointers (#295) --- src/checkother.cpp | 14 +++++++++++++- test/testother.cpp | 13 +++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/checkother.cpp b/src/checkother.cpp index 40abe1453..f38706087 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -964,7 +964,19 @@ void CheckOther::nullPointer() if (tok2->varId() == varid) { if (tok2->next()->str() == "." || Token::Match(tok2->next(), "= %varid% .", varid)) - nullPointerError(tok2); + { + // Is this variable a pointer? + const Token *tok3 = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)]", varid); + if (!tok3) + break; + + if (!tok3->previous() || + Token::Match(tok3->previous(), "[({};]") || + tok3->previous()->isName()) + { + nullPointerError(tok2); + } + } break; } diff --git a/test/testother.cpp b/test/testother.cpp index a01d84df3..6b5381d76 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -59,6 +59,7 @@ private: TEST_CASE(varScope2); TEST_CASE(nullpointer1); + TEST_CASE(nullpointer2); } void check(const char code[]) @@ -411,6 +412,18 @@ private: "}\n"); ASSERT_EQUALS(std::string("[test.cpp:4]: (error) Possible null pointer dereference\n"), errout.str()); } + + void nullpointer2() + { + // Null pointer dereference can only happen with pointers + checkNullPointer("void foo()\n" + "{\n" + " Fred fred;\n" + " while (fred);\n" + " fred.hello();\n" + "}\n"); + ASSERT_EQUALS(std::string(""), errout.str()); + } }; REGISTER_TEST(TestOther)