From a1a14b846586284c2437b073a40d0df63dbe0902 Mon Sep 17 00:00:00 2001 From: Rikard Falkeborn Date: Wed, 10 Jul 2019 09:13:59 +0200 Subject: [PATCH] Fix FP with cast pointer to free() (#1961) This fixes false positives when the pointer passed to free() (or similar deallocation functions) is cast using a c-style cast. --- lib/checkleakautovar.cpp | 3 +++ test/testleakautovar.cpp | 15 +++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp index b2553173a..03dd7bd42 100644 --- a/lib/checkleakautovar.cpp +++ b/lib/checkleakautovar.cpp @@ -778,6 +778,9 @@ void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpenin arg = arg->tokAt(5); } + // Skip casts + while (arg && arg->isCast()) + arg = arg->astOperand2() ? arg->astOperand2() : arg->astOperand1(); const Token * const argTypeStartTok = arg; while (Token::Match(arg, "%name% .|:: %name%")) diff --git a/test/testleakautovar.cpp b/test/testleakautovar.cpp index 7fe1b7036..07c2c2aaa 100644 --- a/test/testleakautovar.cpp +++ b/test/testleakautovar.cpp @@ -64,6 +64,7 @@ private: TEST_CASE(assign16); TEST_CASE(assign17); // #9047 TEST_CASE(assign18); + TEST_CASE(assign19); TEST_CASE(realloc1); TEST_CASE(realloc2); @@ -358,6 +359,14 @@ private: ASSERT_EQUALS("[test.c:3]: (error) Memory leak: p\n", errout.str()); } + void assign19() { + check("void f() {\n" + " char *p = malloc(10);\n" + " free((void*)p);\n" + "}"); + ASSERT_EQUALS("", errout.str()); + } + void realloc1() { check("void f() {\n" " void *p = malloc(10);\n" @@ -1345,6 +1354,12 @@ private: "}"); ASSERT_EQUALS("[test.c:3]: (error) Mismatching allocation and deallocation: f\n", errout.str()); + check("void f() {\n" + " FILE*f=fopen(fname,a);\n" + " free((void*)f);\n" + "}"); + ASSERT_EQUALS("[test.c:3]: (error) Mismatching allocation and deallocation: f\n", errout.str()); + check("void f() {\n" " char *cPtr = new char[100];\n" " delete[] cPtr;\n"