Fixed #2860, False positive: Returning value of strncat() reported as memory leak

http://sourceforge.net/apps/trac/cppcheck/ticket/2860
This commit is contained in:
Reijo Tomperi 2011-06-26 23:53:16 +03:00
parent 382520ee9f
commit 918b4d859f
3 changed files with 45 additions and 1 deletions

View File

@ -286,6 +286,7 @@ Token *Tokenizer::copyTokens(Token *dest, const Token *first, const Token *last)
tok2->isSigned(tok->isSigned());
tok2->isLong(tok->isLong());
tok2->isUnused(tok->isUnused());
tok2->varId(tok->varId());
// Check for links and fix them up
if (tok2->str() == "(" || tok2->str() == "[" || tok2->str() == "{")
@ -4655,6 +4656,8 @@ bool Tokenizer::simplifyTokenList()
}
}
simplifyReturn();
removeRedundantAssignment();
simplifyComma();
@ -8401,7 +8404,6 @@ void Tokenizer::simplifyEnum()
}
}
void Tokenizer::simplifyStd()
{
std::set<std::string> f;
@ -9889,3 +9891,21 @@ void Tokenizer::removeUnnecessaryQualification()
}
}
void Tokenizer::simplifyReturn()
{
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "return strncat ( %any% , %any% , %any% ) ;"))
{
// Change to: strncat ( %any% , %any% , %any% ) ;
tok->deleteNext();
tok->str("strncat");
// Change to: strncat ( %any% , %any% , %any% ) ; return %any% ;
tok->tokAt(8)->insertToken("return");
copyTokens(tok->tokAt(9), tok->tokAt(2), tok->tokAt(2));
tok->tokAt(10)->insertToken(";");
}
}
}

View File

@ -666,6 +666,12 @@ public:
return _varId;
}
/**
* Simplify e.g. 'return(strncat(temp,"a",1));' into
* strncat(temp,"a",1); return temp;
*/
void simplifyReturn();
private:
/** Disable copy constructor, no implementation */
Tokenizer(const Tokenizer &);

View File

@ -358,6 +358,7 @@ private:
TEST_CASE(simplifyIfNotNull);
TEST_CASE(simplifyVarDecl1); // ticket # 2682 segmentation fault
TEST_CASE(simplifyVarDecl2); // ticket # 2834 segmentation fault
TEST_CASE(return_strncat); // ticket # 2860 Returning value of strncat() reported as memory leak
}
std::string tok(const char code[], bool simplify = true)
@ -7080,6 +7081,23 @@ private:
tok(code, false);
ASSERT_EQUALS("", errout.str());
}
void return_strncat()
{
const char code[] = "char *f()\n"
"{\n"
" char *temp=malloc(2);\n"
" strcpy(temp,\"\");\n"
" return (strncat(temp,\"a\",1));\n"
"}";
ASSERT_EQUALS("char * f ( ) { "
"char * temp ; "
"temp = malloc ( 2 ) ; "
"strcpy ( temp , \"\" ) ; "
"strncat ( temp , \"a\" , 1 ) ; "
"return temp ; "
"}", tok(code, true));
}
};
REGISTER_TEST(TestSimplifyTokens)