From a4406aca32a6917d93dc3dfa88e1be0303adebd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sun, 3 Feb 2019 12:15:05 +0100 Subject: [PATCH] Fixed #7845 (Leak reported when ignoring return value of 'new', even if pointer saved by constructor) --- lib/checkmemoryleak.cpp | 8 ++++++++ test/testmemleak.cpp | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp index 1887a0e83..1e64f12e9 100644 --- a/lib/checkmemoryleak.cpp +++ b/lib/checkmemoryleak.cpp @@ -142,6 +142,14 @@ CheckMemoryLeak::AllocType CheckMemoryLeak::getAllocationType(const Token *tok2, return No; if (tok2->astOperand1() && (tok2->astOperand1()->str() == "[" || (tok2->astOperand1()->astOperand1() && tok2->astOperand1()->astOperand1()->str() == "["))) return NewArray; + const Token *typeTok = tok2->next(); + while (Token::Match(typeTok, "%name% :: %name%")) + typeTok = typeTok->tokAt(2); + if (typeTok->type() && typeTok->type()->isClassType()) { + const Scope *classScope = typeTok->type()->classScope; + if (classScope && classScope->numConstructors > 0) + return No; + } return New; } diff --git a/test/testmemleak.cpp b/test/testmemleak.cpp index dcd6a0114..ae35d3bbd 100644 --- a/test/testmemleak.cpp +++ b/test/testmemleak.cpp @@ -1804,6 +1804,9 @@ private: // pass allocated memory to function using a smart pointer TEST_CASE(smartPointerFunctionParam); TEST_CASE(resourceLeak); + + // Test getAllocationType for subfunction + TEST_CASE(getAllocationType); } void functionParameter() { @@ -2087,6 +2090,17 @@ private: "}\n"); ASSERT_EQUALS("", errout.str()); } + + void getAllocationType() { + // #7845 + check("class Thing { Thing(); };\n" + "Thing * makeThing() { Thing *thing = new Thing; return thing; }\n" + "\n" + "void f() {\n" + " makeThing();\n" + "}"); + ASSERT_EQUALS("", errout.str()); + } }; REGISTER_TEST(TestMemleakNoVar)