Fixed #842 (out of bounds: when buffer is allocated with malloc)

http://sourceforge.net/apps/trac/cppcheck/ticket/842
This commit is contained in:
Slava Semushin 2009-11-15 18:38:57 +06:00
parent 3911dd79cb
commit 6669a50634
2 changed files with 23 additions and 0 deletions

View File

@ -669,6 +669,17 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable()
type = "char"; type = "char";
varid = tok->tokAt(1)->varId(); varid = tok->tokAt(1)->varId();
nextTok = 7; nextTok = 7;
// "int * x ; x = malloc (y);"
const Token *declTok = tok->tokAt(-3);
if (varid > 0 && declTok && Token::Match(declTok, "%type% * %varid% ;", varid))
{
type = declTok->strAt(0);
// malloc() gets count of bytes and not count of
// elements, so we should calculate count of elements
// manually
size /= _tokenizer->sizeOfType(declTok);
}
} }
else else
{ {

View File

@ -91,6 +91,7 @@ private:
TEST_CASE(array_index_20); TEST_CASE(array_index_20);
TEST_CASE(array_index_21); TEST_CASE(array_index_21);
TEST_CASE(array_index_22); TEST_CASE(array_index_22);
TEST_CASE(array_index_23);
TEST_CASE(array_index_multidim); TEST_CASE(array_index_multidim);
TEST_CASE(buffer_overrun_1); TEST_CASE(buffer_overrun_1);
@ -681,6 +682,17 @@ private:
ASSERT_EQUALS("[test.cpp:4]: (error) Array index out of bounds\n", errout.str()); ASSERT_EQUALS("[test.cpp:4]: (error) Array index 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 index out of bounds\n", errout.str());
}
void array_index_multidim() void array_index_multidim()
{ {
check("void f()\n" check("void f()\n"