diff --git a/src/checkother.cpp b/src/checkother.cpp index 886b40f1b..a69b30cef 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -1028,8 +1028,12 @@ void CheckOther::nullPointer() // 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%")) + if (Token::Match(tok1, "[{};] %var% = %var% . %var%")) { + if (std::string(tok1->strAt(1)) == tok1->strAt(3)) + continue; + + tok1 = tok1->tokAt(3); const unsigned int varid1(tok1->varId()); if (varid1 == 0) continue; @@ -1039,12 +1043,14 @@ void CheckOther::nullPointer() { 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)) diff --git a/test/testother.cpp b/test/testother.cpp index 9e865c919..75ae08ff7 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -60,6 +60,7 @@ private: TEST_CASE(nullpointer2); TEST_CASE(nullpointer3); TEST_CASE(nullpointer4); + TEST_CASE(nullpointer5); TEST_CASE(oldStylePointerCast); } @@ -468,6 +469,27 @@ private: ASSERT_EQUALS("[test.cpp:3]: (error) Possible null pointer dereference\n", errout.str()); } + void nullpointer5() + { + // ok dereferencing in a condition + checkNullPointer("void foo(struct ABC *abc)\n" + "{\n" + " if (abc && abc->a);\n" + " if (!abc)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + + // ok to use a linked list.. + checkNullPointer("void foo(struct ABC *abc)\n" + "{\n" + " abc = abc->next;\n" + " if (!abc)\n" + " ;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } + void checkOldStylePointerCast(const char code[]) { // Tokenize..