Fix #11406 FP returnDanglingLifetime, std::unique_ptr and implicit conversion to bool (#4600)

This commit is contained in:
chrchr-github 2022-11-27 09:24:19 +01:00 committed by GitHub
parent 4cb49013a7
commit 665e4230f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 1 deletions

View File

@ -578,7 +578,8 @@ void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token
}
}
}
const bool escape = Token::Match(tok->astParent(), "return|throw");
const bool escape = Token::simpleMatch(tok->astParent(), "throw") ||
(Token::simpleMatch(tok->astParent(), "return") && !Function::returnsStandardType(scope->function));
std::unordered_set<const Token*> exprs;
for (const ValueFlow::Value& val:tok->values()) {
if (!val.isLocalLifetimeValue() && !val.isSubFunctionLifetimeValue())

View File

@ -2931,6 +2931,13 @@ bool Function::returnsReference(const Function* function, bool unknown)
});
}
bool Function::returnsStandardType(const Function* function, bool unknown)
{
return checkReturns(function, unknown, true, [](UNUSED const Token* defStart, const Token* defEnd) {
return defEnd->previous() && defEnd->previous()->isStandardType();
});
}
bool Function::returnsVoid(const Function* function, bool unknown)
{
return checkReturns(function, unknown, true, [](UNUSED const Token* defStart, const Token* defEnd) {

View File

@ -930,6 +930,7 @@ public:
static bool returnsConst(const Function* function, bool unknown = false);
static bool returnsReference(const Function* function, bool unknown = false);
static bool returnsStandardType(const Function* function, bool unknown = false);
static bool returnsVoid(const Function* function, bool unknown = false);

View File

@ -2768,6 +2768,22 @@ private:
ASSERT_EQUALS(
"[test.cpp:2] -> [test.cpp:1] -> [test.cpp:3]: (error) Returning pointer to local variable 'p' that will be invalid when returning.\n",
errout.str());
check("int* f();\n" // #11406
"bool g() {\n"
" std::unique_ptr<int> ptr(f());\n"
" return ptr.get();\n"
"}\n");
ASSERT_EQUALS("", errout.str());
check("int* f();\n"
"int* g() {\n"
" std::unique_ptr<int> ptr(f());\n"
" return ptr.get();\n"
"}\n");
ASSERT_EQUALS(
"[test.cpp:4] -> [test.cpp:3] -> [test.cpp:4]: (error) Returning object that points to local variable 'ptr' that will be invalid when returning.\n",
errout.str());
}
void danglingLifetime() {
check("auto f() {\n"