From 6669a506342179fcc9555ce18d5a9385e4633ad7 Mon Sep 17 00:00:00 2001 From: Slava Semushin Date: Sun, 15 Nov 2009 18:38:57 +0600 Subject: [PATCH] Fixed #842 (out of bounds: when buffer is allocated with malloc) http://sourceforge.net/apps/trac/cppcheck/ticket/842 --- lib/checkbufferoverrun.cpp | 11 +++++++++++ test/testbufferoverrun.cpp | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index 18a1880b6..e58e0021c 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -669,6 +669,17 @@ void CheckBufferOverrun::checkGlobalAndLocalVariable() type = "char"; varid = tok->tokAt(1)->varId(); 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 { diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index 3e4200505..d75042d4b 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -91,6 +91,7 @@ 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(buffer_overrun_1); @@ -681,6 +682,17 @@ private: 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() { check("void f()\n"