Fixed #547 (index out of bounds not detected when addition used as array index)

http://sourceforge.net/apps/trac/cppcheck/ticket/547
This commit is contained in:
Slava Semushin 2009-08-02 14:55:42 +07:00
parent 0445edf6fe
commit 342acaaaf2
2 changed files with 64 additions and 0 deletions

View File

@ -149,6 +149,22 @@ void CheckBufferOverrun::checkScope(const Token *tok, const char *varname[], con
arrayIndexOutOfBounds(tok->next());
}
}
else if (Token::Match(tok, "%varid% [ %var% + %num% ]", varid))
{
const char *num = tok->strAt(4);
if (std::strtol(num, NULL, 10) >= size)
{
arrayIndexOutOfBounds(tok->next());
}
}
else if (Token::Match(tok, "%varid% [ %num% + %var% ]", varid))
{
const char *num = tok->strAt(2);
if (std::strtol(num, NULL, 10) >= size)
{
arrayIndexOutOfBounds(tok->next());
}
}
}
else if (!tok->isName() && !Token::Match(tok, "[.&]") && Token::Match(tok->next(), std::string(varnames + " [ %num% ]").c_str()))
{

View File

@ -83,6 +83,10 @@ private:
TEST_CASE(array_index_11);
TEST_CASE(array_index_12);
TEST_CASE(array_index_13);
TEST_CASE(array_index_14);
TEST_CASE(array_index_15);
TEST_CASE(array_index_16);
TEST_CASE(array_index_17);
TEST_CASE(buffer_overrun_1);
TEST_CASE(buffer_overrun_2);
@ -432,6 +436,50 @@ private:
ASSERT_EQUALS("", errout.str());
}
void array_index_14()
{
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i+10] = i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (possible error) Array index out of bounds\n", errout.str());
}
void array_index_15()
{
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[10+i] = i;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:5]: (possible error) Array index out of bounds\n", errout.str());
}
void array_index_16()
{
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i+1] = i;\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:5]: (possible error) Array index out of bounds\n", errout.str());
}
void array_index_17()
{
check("void f()\n"
"{\n"
" int a[10];\n"
" for (int i = 0; i < 10; i++)\n"
" a[i*2] = i;\n"
"}\n");
TODO_ASSERT_EQUALS("[test.cpp:5]: (possible error) Array index out of bounds\n", errout.str());
}
void buffer_overrun_1()
{
check("void f()\n"