Fix #1548 (False positive: array index out of bounds in for-loop)

http://sourceforge.net/apps/trac/cppcheck/ticket/1548
This commit is contained in:
Reijo Tomperi 2010-04-01 22:35:36 +03:00
parent 2825773918
commit c7d36b73ed
2 changed files with 31 additions and 1 deletions

View File

@ -470,7 +470,19 @@ void CheckBufferOverrun::checkScope(const Token *tok, const std::vector<std::str
if (max <= size) if (max <= size)
condition_out_of_bounds = false; condition_out_of_bounds = false;
} }
else if (! Token::Match(tok3, "++|--| %varid% ++|--| )", counter_varid)) else if (Token::Match(tok3, "--| %varid% --| )", counter_varid))
{
if (MathLib::toLongNumber(min_counter_value) < MathLib::toLongNumber(max_counter_value))
{
// Code relies on the fact that integer will overflow:
// for (unsigned int i = 3; i < 5; --i)
// Set min value in this case to zero.
max_counter_value = min_counter_value;
min_counter_value = "0";
}
}
else if (! Token::Match(tok3, "++| %varid% ++| )", counter_varid))
{ {
continue; continue;
} }

View File

@ -990,6 +990,24 @@ private:
" }\n" " }\n"
"}\n"); "}\n");
ASSERT_EQUALS("[test.cpp:5]: (error) Buffer access out-of-bounds\n", errout.str()); ASSERT_EQUALS("[test.cpp:5]: (error) Buffer access out-of-bounds\n", errout.str());
check("void f()\n"
"{\n"
" char val[5];\n"
" for (unsigned int i = 3; i < 5; --i) {\n"
" val[i+1] = val[i];\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("void f()\n"
"{\n"
" char val[5];\n"
" for (int i = 3; i < 5; --i) {\n"
" val[i+1] = val[i];\n"
" }\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:5]: (error) Array 'val[5]' index -1 out of bounds\n", errout.str());
} }
void buffer_overrun_1() void buffer_overrun_1()