diff --git a/src/checkother.cpp b/src/checkother.cpp index eddbd3202..d582f12ff 100644 --- a/src/checkother.cpp +++ b/src/checkother.cpp @@ -878,7 +878,7 @@ void CheckOther::nullPointer() if (tok2->next()->str() == "." || Token::Match(tok2->next(), "= %varid% .", varid)) { // Is this variable a pointer? - const Token *tok3 = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)]", varid); + const Token *tok3 = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)=]", varid); if (!tok3) break; @@ -956,7 +956,11 @@ void CheckOther::nullPointer() { if (indentlevel4 <= 1) { - nullPointerError(tok1, varname); + // Is this variable a pointer? + const Token *tempTok = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)=]", varid); + if (tempTok) + nullPointerError(tok1, varname); + break; } --indentlevel4; @@ -1037,7 +1041,10 @@ void CheckOther::nullPointer() else if (Token::Match(tok2, "if ( !| %varid% )", varid1)) { - nullPointerError(tok1, varname, tok2->linenr()); + // Is this variable a pointer? + const Token *tempTok = Token::findmatch(_tokenizer->tokens(), "%type% * %varid% [;)=]", varid1); + if (tempTok) + nullPointerError(tok1, varname, tok2->linenr()); break; } } diff --git a/test/testother.cpp b/test/testother.cpp index e8a94701d..3f5aad336 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -65,6 +65,7 @@ private: TEST_CASE(nullpointer2); TEST_CASE(nullpointer3); // dereferencing struct and then checking if it's null TEST_CASE(nullpointer4); + TEST_CASE(nullpointer5); // References should not be checked TEST_CASE(oldStylePointerCast); @@ -632,6 +633,16 @@ private: "}\n"); ASSERT_EQUALS("[test.cpp:3]: (error) Possible null pointer dereference: tok\n", errout.str()); + checkNullPointer("void foo(Token &tok)\n" + "{\n" + " for (int i = 0; i < tok.size(); i++ )\n" + " {\n" + " while (!tok)\n" + " char c = tok.read();\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + checkNullPointer("void foo()\n" "{\n" " for (const Token *tok = tokens; tok; tok = tok->next())\n" @@ -862,8 +873,17 @@ private: ASSERT_EQUALS("", errout.str()); } - - + void nullpointer5() + { + // errors.. + checkNullPointer("void foo(A &a)\n" + "{\n" + " char c = a.c();\n" + " if (!a)\n" + " return;\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); + } void checkOldStylePointerCast(const char code[]) {