Fixed #1646 (False positive: array access after return cannot have default loop value)

This commit is contained in:
Daniel Marjamäki 2010-05-18 19:55:23 +02:00
parent 2bced1d90c
commit f87eb774eb
2 changed files with 64 additions and 16 deletions

View File

@ -5067,6 +5067,29 @@ bool Tokenizer::simplifyKnownVariables()
if (Token::Match(tok2->tokAt(-2), "for ( %varid% = %num% ; %varid% <|<= %num% ; ++| %varid% ++| ) {", varid)) if (Token::Match(tok2->tokAt(-2), "for ( %varid% = %num% ; %varid% <|<= %num% ; ++| %varid% ++| ) {", varid))
{ {
// is there a "break" in the for loop?
bool hasbreak = false;
unsigned int indentlevel4 = 0; // indentlevel for tok4
for (const Token *tok4 = tok2->previous()->link(); tok4; tok4 = tok4->next())
{
if (tok4->str() == "{")
++indentlevel4;
else if (tok4->str() == "}")
{
if (indentlevel4 <= 1)
break;
--indentlevel4;
}
else if (tok4->str() == "break")
{
hasbreak = true;
break;
}
}
if (hasbreak)
break;
// no break => the value of the counter value is known after the for loop..
const std::string compareop = tok2->strAt(5); const std::string compareop = tok2->strAt(5);
if (compareop == "<") if (compareop == "<")
value = tok2->strAt(6); value = tok2->strAt(6);

View File

@ -1152,23 +1152,48 @@ private:
void simplifyKnownVariables24() void simplifyKnownVariables24()
{ {
// This testcase is related to ticket #1596 {
const char code[] = "void foo()\n" // This testcase is related to ticket #1596
"{\n" const char code[] = "void foo()\n"
" int c;\n" "{\n"
" for (c=0;c<10;++c) { }\n" " int c;\n"
" a[c] = 0;\n" " for (c=0;c<10;++c) { }\n"
"}\n"; " a[c] = 0;\n"
"}\n";
// Current result ASSERT_EQUALS(
ASSERT_EQUALS( "void foo ( ) "
"void foo ( ) " "{"
"{" " int c ;"
" int c ;" " for ( c = 0 ; c < 10 ; ++ c ) { }"
" for ( c = 0 ; c < 10 ; ++ c ) { }" " a [ 10 ] = 0 ; "
" a [ 10 ] = 0 ; " "}",
"}", simplifyKnownVariables(code));
simplifyKnownVariables(code)); }
{
// #1692 - unknown counter value after for loop
const char code[] = "void foo(const char s[])\n"
"{\n"
" int x[3];\n"
" int i;\n"
" for (i = 0; i < 3; ++i) {\n"
" if (s[i]) break;\n"
" }"
" if (i < 3) x[i] = 0;\n"
"}\n";
ASSERT_EQUALS(
"void foo ( const char s [ ] ) "
"{"
" int x [ 3 ] ;"
" int i ;"
" for ( i = 0 ; i < 3 ; ++ i ) {"
" if ( s [ i ] ) { break ; }"
" }"
" if ( i < 3 ) { x [ i ] = 0 ; } "
"}",
simplifyKnownVariables(code));
}
} }
void simplifyKnownVariables25() void simplifyKnownVariables25()