Fix issue 9639: False positive: Returning object that points to local variable that will be invalid when returning (#2576)

* Follow reference when tracking local variables

* Fix issue 9639: False positive: Returning object that points to local variable that will be invalid when returning
This commit is contained in:
Paul Fultz II 2020-03-23 16:54:53 -05:00 committed by GitHub
parent 46222d58ef
commit 5462e43161
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 31 deletions

View File

@ -505,7 +505,8 @@ void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token
for (const ValueFlow::Value& val:tok->values()) {
if (!val.isLocalLifetimeValue())
continue;
const Token * tokvalue = getParentLifetime(val.tokvalue);
for(const LifetimeToken& lt :getLifetimeTokens(getParentLifetime(val.tokvalue))) {
const Token * tokvalue = lt.token;
if (Token::Match(tok->astParent(), "return|throw")) {
if (getPointerDepth(tok) < getPointerDepth(tokvalue))
continue;
@ -541,6 +542,7 @@ void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token
}
}
}
}
const Token *lambdaEndToken = findLambdaEndToken(tok);
if (lambdaEndToken) {
checkVarLifetimeScope(lambdaEndToken->link(), lambdaEndToken);

View File

@ -2261,6 +2261,17 @@ private:
" ptr = &arr[2];\n"
"}\n");
ASSERT_EQUALS("", errout.str());
// #9639
check("struct Fred {\n"
" std::string s;\n"
"};\n"
"const Fred &getFred();\n"
"const char * f() {\n"
" const Fred &fred = getFred();\n"
" return fred.s.c_str();\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}
void danglingLifetimeFunction() {