From ccba934cb1dc847bdf169d4743b90c05a2e2b0d5 Mon Sep 17 00:00:00 2001 From: Alexander Mai Date: Thu, 17 Apr 2014 21:32:56 +0200 Subject: [PATCH] #5684 The scope of the variable 'p' can be reduced - But it can not. --- lib/checkother.cpp | 7 +++++++ test/testother.cpp | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 3c7e7b3b6..932e478cd 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -1882,6 +1882,7 @@ bool CheckOther::checkInnerScope(const Token *tok, const Variable* var, bool& us } } + bool bFirstAssignment=false; for (; tok != end; tok = tok->next()) { if (tok->str() == "goto") return false; @@ -1918,6 +1919,12 @@ bool CheckOther::checkInnerScope(const Token *tok, const Variable* var, bool& us if (Token::Match(tok, "& %varid%", var->declarationId())) // Taking address of variable return false; + if (Token::Match(tok, "%varid% = %any%", var->declarationId())) + bFirstAssignment = true; + + if (!bFirstAssignment && Token::Match(tok, "* %varid%", var->declarationId())) // dereferencing means access to previous content + return false; + if (Token::Match(tok, "= %varid%", var->declarationId()) && (var->isArray() || var->isPointer())) // Create a copy of array/pointer. Bailout, because the memory it points to might be necessary in outer scope return false; diff --git a/test/testother.cpp b/test/testother.cpp index 53bd28c87..7c52c7f78 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -83,6 +83,7 @@ private: TEST_CASE(varScope19); // Ticket #4994 TEST_CASE(varScope20); // Ticket #5103 TEST_CASE(varScope21); // Ticket #5382 + TEST_CASE(varScope22); // Ticket #5684 TEST_CASE(oldStylePointerCast); TEST_CASE(invalidPointerCast); @@ -1256,6 +1257,32 @@ private: ASSERT_EQUALS("", errout.str()); } + void varScope22() { // Ticket #5684 - "The scope of the variable 'p' can be reduced" - But it can not. + varScope("void foo() {\n" + " int* p( 42 );\n" + " int i = 0;\n" + " while ( i != 100 ) {\n" + " *p = i;\n" + " ++p;\n" + " ++i;\n" + " }\n" + "}"); + ASSERT_EQUALS("", errout.str()); + // try to avoid an obvious false negative after applying the fix for the example above: + varScope("void foo() {\n" + " int* p( 42 );\n" + " int i = 0;\n" + " int dummy = 0;\n" + " while ( i != 100 ) {\n" + " p = & dummy;\n" + " *p = i;\n" + " ++p;\n" + " ++i;\n" + " }\n" + "}"); + ASSERT_EQUALS("[test.cpp:2]: (style) The scope of the variable 'p' can be reduced.\n", errout.str()); + } + void checkOldStylePointerCast(const char code[]) { // Clear the error buffer.. errout.str("");