From a1078f446a9e7d9b568ecb15c10a8fb28a6a5b8f Mon Sep 17 00:00:00 2001 From: Paul Fultz II Date: Wed, 13 Sep 2023 14:26:37 -0500 Subject: [PATCH] Fix 11980: False positive returnDanglingLifetime returning pointer to stack array as std::string (by way of struct return value constructor) (#5445) --- lib/astutils.cpp | 3 ++- lib/valueflow.cpp | 2 +- test/testautovariables.cpp | 9 +++++++++ 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/astutils.cpp b/lib/astutils.cpp index 3844333e6..847e41416 100644 --- a/lib/astutils.cpp +++ b/lib/astutils.cpp @@ -724,7 +724,8 @@ std::vector getParentValueTypes(const Token* tok, const Settings* set const Scope* scope = t->classScope; // Check for aggregate constructors if (scope && scope->numConstructors == 0 && t->derivedFrom.empty() && - (t->isClassType() || t->isStructType()) && numberOfArguments(ftok) < scope->varlist.size()) { + (t->isClassType() || t->isStructType()) && numberOfArguments(ftok) <= scope->varlist.size() && + !scope->varlist.empty()) { assert(argn < scope->varlist.size()); auto it = std::next(scope->varlist.cbegin(), argn); if (it->valueType()) diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index a63062862..0f34206de 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -4602,7 +4602,7 @@ static void valueFlowLifetimeClassConstructor(Token* tok, const Variable& var = *it; if (var.isReference() || var.isRValueReference()) { ls.byRef(tok, tokenlist, errorLogger, settings); - } else { + } else if (ValueFlow::isLifetimeBorrowed(ls.argtok, settings)) { ls.byVal(tok, tokenlist, errorLogger, settings); } it++; diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index aed96118c..2978f54dd 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -3750,6 +3750,15 @@ private: " return A{y, x};\n" "}"); ASSERT_EQUALS("", errout.str()); + + check("struct a {\n" + " std::string m;\n" + "};\n" + "a f() {\n" + " std::array m {};\n" + " return { m.data() };\n" + "}\n"); + ASSERT_EQUALS("", errout.str()); } void danglingLifetimeInitList() {