#5684 The scope of the variable 'p' can be reduced - But it can not.
This commit is contained in:
parent
064844f8db
commit
ccba934cb1
|
@ -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;
|
||||
|
||||
|
|
|
@ -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("");
|
||||
|
|
Loading…
Reference in New Issue