From b7ba49114cb17670fc70e30b537bb09d182f879d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Mon, 20 Jul 2009 18:53:41 +0200 Subject: [PATCH] Fixed #485 (detect when code is checking for null after dereferencing) --- src/checkother.cpp | 26 ++++++++++++++++++++++++++ test/testother.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/src/checkother.cpp b/src/checkother.cpp index 8772d9730..87c57c7cc 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -1024,6 +1024,32 @@ void CheckOther::nullPointer() tok2 = tok2->next(); } } + + // Dereferencing a pointer and then checking if it's NULL.. + for (const Token *tok1 = _tokenizer->tokens(); tok1; tok1 = tok1->next()) + { + if (Token::Match(tok1, "%var% . %var%")) + { + const unsigned int varid1(tok1->varId()); + unsigned int indentlevel2 = 0; + for (const Token *tok2 = tok1->tokAt(3); tok2; tok2 = tok2->next()) + { + if (tok2->str() == "{") + ++indentlevel2; + else if (tok2->str() == "}") + { + if (indentlevel2 == 0) + break; + --indentlevel2; + } + else if (tok2->str() == "if") + { + if (Token::Match(tok2, "if ( !| %varid% )", varid1)) + nullPointerError(tok1); + } + } + } + } } diff --git a/test/testother.cpp b/test/testother.cpp index 1b5e6b7c4..9e865c919 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -58,6 +58,8 @@ private: TEST_CASE(nullpointer1); TEST_CASE(nullpointer2); + TEST_CASE(nullpointer3); + TEST_CASE(nullpointer4); TEST_CASE(oldStylePointerCast); } @@ -444,6 +446,28 @@ private: ASSERT_EQUALS("", errout.str()); } + void nullpointer3() + { + checkNullPointer("void foo(struct ABC *abc)\n" + "{\n" + " int *a = abc->a;\n" + " if (!abc)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3]: (error) Possible null pointer dereference\n", errout.str()); + } + + void nullpointer4() + { + checkNullPointer("void foo(struct ABC *abc)\n" + "{\n" + " int *a = abc->a;\n" + " if (abc)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3]: (error) Possible null pointer dereference\n", errout.str()); + } + void checkOldStylePointerCast(const char code[]) { // Tokenize..