From efd488b51908ea89fde33a178c7b223f6ad2cde6 Mon Sep 17 00:00:00 2001 From: chrchr-github <78114321+chrchr-github@users.noreply.github.com> Date: Fri, 13 Oct 2023 18:47:06 +0200 Subject: [PATCH] Partial fix for #12062 FN: memleak (#5548) --- lib/checkleakautovar.cpp | 20 +++++++++++++------- test/testleakautovar.cpp | 8 ++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp index efd319f3dcb..47cb070b934 100644 --- a/lib/checkleakautovar.cpp +++ b/lib/checkleakautovar.cpp @@ -60,6 +60,18 @@ static const int NEW = -1; static const std::array, 4> alloc_failed_conds {{{"==", "0"}, {"<", "0"}, {"==", "-1"}, {"<=", "-1"}}}; static const std::array, 4> alloc_success_conds {{{"!=", "0"}, {">", "0"}, {"!=", "-1"}, {">=", "0"}}}; +static bool isAutoDeallocType(const Type* type) { + if (!type) + return true; + if (type->classScope && type->classScope->numConstructors == 0 && + (type->classScope->varlist.empty() || type->needInitialization == Type::NeedInitialization::True) && + std::none_of(type->derivedFrom.cbegin(), type->derivedFrom.cend(), [](const Type::BaseInfo& bi) { + return isAutoDeallocType(bi.type); + })) + return false; + return true; +} + /** * @brief Is variable type some class with automatic deallocation? * @param var variable token @@ -72,14 +84,8 @@ static bool isAutoDealloc(const Variable *var) // return false if the type is a simple record type without side effects // a type that has no side effects (no constructors and no members with constructors) - /** @todo false negative: check base class for side effects */ /** @todo false negative: check constructors for side effects */ - if (var->typeScope() && var->typeScope()->numConstructors == 0 && - (var->typeScope()->varlist.empty() || var->type()->needInitialization == Type::NeedInitialization::True) && - var->type()->derivedFrom.empty()) - return false; - - return true; + return isAutoDeallocType(var->type()); } template diff --git a/test/testleakautovar.cpp b/test/testleakautovar.cpp index ccb623bdb6b..4e14612206e 100644 --- a/test/testleakautovar.cpp +++ b/test/testleakautovar.cpp @@ -601,6 +601,14 @@ class TestLeakAutoVar : public TestFixture { " b = Bar(*new Foo(data));\n" "}", /*cpp*/ true); ASSERT_EQUALS("[test.cpp:4]: (information) --check-library: Function Foo() should have / configuration\n", errout.str()); + + check("class B {};\n" + " class D : public B {};\n" + " void g() {\n" + " auto d = new D();\n" + " if (d) {}\n" + "}", /*cpp*/ true); + ASSERT_EQUALS("[test.cpp:6]: (error) Memory leak: d\n", errout.str()); } void realloc1() {