From ad5d87ee1487efc33508248684751faff41bb8e5 Mon Sep 17 00:00:00 2001 From: Reijo Tomperi Date: Thu, 8 Oct 2009 11:55:37 +0300 Subject: [PATCH] Fix #802 (possible null pointer dereference reported for reference) http://sourceforge.net/apps/trac/cppcheck/ticket/802 --- src/checkother.cpp | 13 ++++++++++--- test/testother.cpp | 24 ++++++++++++++++++++++-- 2 files changed, 32 insertions(+), 5 deletions(-) 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[]) {