Fix #1340 (False positive: Array out of bounds for re-initialised array pointer)

http://sourceforge.net/apps/trac/cppcheck/ticket/1340
This commit is contained in:
Reijo Tomperi 2010-02-10 23:11:08 +02:00
parent 0a6aa0f094
commit 2a78637da7
2 changed files with 55 additions and 12 deletions

View File

@ -203,6 +203,12 @@ void CheckBufferOverrun::checkScope(const Token *tok, const char *varname[], con
return;
}
if (varid != 0 && Token::Match(tok, "%varid% = new|malloc|realloc", varid))
{
// Abort
break;
}
// Array index..
if (varid > 0)
{

View File

@ -92,7 +92,6 @@ private:
TEST_CASE(array_index_20);
TEST_CASE(array_index_21);
TEST_CASE(array_index_22);
TEST_CASE(array_index_23);
TEST_CASE(array_index_multidim);
TEST_CASE(array_index_switch_in_for);
TEST_CASE(array_index_calculation);
@ -736,17 +735,6 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error) Array 'indices[2]' index 2 out of bounds\n", errout.str());
}
void array_index_23()
{
// ticket #842
check("void f() {\n"
" int *tab4 = malloc(20 * sizeof(int));\n"
" tab4[20] = 0;\n"
" free(tab4);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'tab4[20]' index 20 out of bounds\n", errout.str());
}
void array_index_multidim()
{
check("void f()\n"
@ -1374,6 +1362,55 @@ private:
" s[10] = 0;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:4]: (error) Array 's[10]' index 10 out of bounds\n", errout.str());
check("void foo()\n"
"{\n"
"char * buf = new char[8];\n"
"buf[7] = 0;\n"
"delete [] buf;\n"
"buf = new char[9];\n"
"buf[8] = 0;\n"
"delete [] buf;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("void foo()\n"
"{\n"
"char * buf = new char[8];\n"
"buf[7] = 0;\n"
"delete [] buf;\n"
"buf = new char[9];\n"
"buf[9] = 0;\n"
"delete [] buf;\n"
"}\n");
ASSERT_EQUALS("[test.cpp:7]: (error) Array 'buf[9]' index 9 out of bounds\n", errout.str());
// ticket #842
check("void f() {\n"
" int *tab4 = malloc(20 * sizeof(int));\n"
" tab4[20] = 0;\n"
" free(tab4);\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Array 'tab4[20]' index 20 out of bounds\n", errout.str());
check("void f() {\n"
" int *tab4 = malloc(20 * sizeof(int));\n"
" tab4[19] = 0;\n"
" free(tab4);\n"
" tab4 = malloc(21 * sizeof(int));\n"
" tab4[20] = 0;\n"
" free(tab4);\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("void f() {\n"
" int *tab4 = malloc(20 * sizeof(int));\n"
" tab4[19] = 0;\n"
" tab4 = realloc(tab4,21 * sizeof(int));\n"
" tab4[20] = 0;\n"
" free(tab4);\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}