#3434 (False positive Returning reference to auto variable)

This commit is contained in:
Daniel Marjamäki 2011-12-26 07:44:16 +01:00
parent 385afffb14
commit 096b22c46e
2 changed files with 28 additions and 3 deletions

View File

@ -295,10 +295,24 @@ void CheckAutoVariables::returnReference()
// return..
if (Token::Match(tok2, "return %var% ;")) {
// is the returned variable a local variable?
const unsigned int varid = tok2->next()->varId();
const Variable *var = symbolDatabase->getVariableFromVarId(varid);
const unsigned int varid1 = tok2->next()->varId();
const Variable *var1 = symbolDatabase->getVariableFromVarId(varid1);
if (var && var->isLocal() && !var->isStatic()) {
if (var1 && var1->isLocal() && !var1->isStatic()) {
// If reference variable is used, check what it references
if (Token::Match(var1->nameToken()->previous(), "& %var% ="))
{
const Token *tok3 = var1->nameToken()->tokAt(2);
if (!Token::Match(tok3, "%var% [;.]"))
continue;
// Only report error if variable that is referenced is
// a auto variable
const Variable *var2 = symbolDatabase->getVariableFromVarId(tok3->varId());
if (!var2 || !var2->isLocal() || var2->isStatic())
continue;
}
// report error..
errorReturnReference(tok2);
}

View File

@ -83,6 +83,7 @@ private:
TEST_CASE(returnReference1);
TEST_CASE(returnReference2);
TEST_CASE(returnReference3);
TEST_CASE(returnReference4);
// return c_str()..
TEST_CASE(returncstr1);
@ -466,6 +467,16 @@ private:
ASSERT_EQUALS("", errout.str());
}
// Returning reference to global variable
void returnReference4() {
check("double a;\n"
"double & f() {\n"
" double & ref = a;\n"
" return ref;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
}
void returncstr1() {
check("const char *foo()\n"
"{\n"