From f3bf14ba13345262d71971d381b2139222cfcc16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Thu, 4 Nov 2010 21:09:32 +0100 Subject: [PATCH] Fixed #2171 (false positive: possible nullpointer dereference) --- lib/checknullpointer.cpp | 8 +++++++- test/testnullpointer.cpp | 13 +++++++++++-- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/checknullpointer.cpp b/lib/checknullpointer.cpp index cb8ed8898..ed997ff78 100644 --- a/lib/checknullpointer.cpp +++ b/lib/checknullpointer.cpp @@ -436,14 +436,20 @@ void CheckNullPointer::nullPointerByDeRefAndChec() void CheckNullPointer::nullPointerByCheckAndDeRef() { // Check if pointer is NULL and then dereference it.. + std::set pointerVariables; for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next()) { - if (Token::Match(tok, "if ( ! %var% ) {")) + if (Token::Match(tok, "* %var% [;,)=]")) + pointerVariables.insert(tok->next()->varId()); + + else if (Token::Match(tok, "if ( ! %var% ) {")) { bool null = true; const unsigned int varid(tok->tokAt(3)->varId()); if (varid == 0) continue; + if (pointerVariables.find(varid) == pointerVariables.end()) + continue; unsigned int indentlevel = 1; for (const Token *tok2 = tok->tokAt(6); tok2; tok2 = tok2->next()) { diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index 35e732fda..209c48f05 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -672,20 +672,29 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); - check("void foo() {\n" + check("void foo(char *p) {\n" " if (!p) {\n" " switch (x) { }\n" " }\n" "}\n"); ASSERT_EQUALS("", errout.str()); - check("void foo(bool p) {\n" + check("void foo(char *p) {\n" " if (!p) {\n" " }\n" " return *x;\n" "}\n"); ASSERT_EQUALS("", errout.str()); + // operator! + check("void f() {\n" + " A a;\n" + " if (!a) {\n" + " a.x();\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + // This is why this check can't be used on the simplified token list check("void f(Foo *foo) {\n" " if (!dynamic_cast(foo)) {\n"