Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 43 additions & 30 deletions lib/tokenize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4076,36 +4076,6 @@ bool Tokenizer::simplifyTokenList()

simplifyCasts();

// simplify "x=realloc(y,0);" => "free(y); x=0;"..
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "; %var% = realloc ( %var% , 0 ) ;"))
{
const std::string varname(tok->next()->str());
const unsigned int varid(tok->next()->varId());

// Delete the "%var% ="
tok->deleteNext();
tok->deleteNext();

// Change function name "realloc" to "free"
tok->next()->str("free");

// delete the ", 0"
Token::eraseTokens(tok->tokAt(3), tok->tokAt(6));

// goto the ";"
tok = tok->tokAt(5);

// insert "var=0;"
tok->insertToken(";");
tok->insertToken("0");
tok->insertToken("=");
tok->insertToken(varname);
tok->next()->varId(varid);
}
}

// Simplify simple calculations..
simplifyCalculations();

Expand Down Expand Up @@ -4145,6 +4115,49 @@ bool Tokenizer::simplifyTokenList()
}
}

// simplify "x=realloc(y,0);" => "free(y); x=0;"..
// and "x = realloc (0, n);" => "x = malloc(n);"
for (Token *tok = _tokens; tok; tok = tok->next())
{
if (Token::Match(tok, "; %var% = realloc ( %var% , 0 ) ;"))
{
const std::string varname(tok->next()->str());
const unsigned int varid(tok->next()->varId());

// Delete the "%var% ="
tok->deleteNext();
tok->deleteNext();

// Change function name "realloc" to "free"
tok->next()->str("free");

// delete the ", 0"
Token::eraseTokens(tok->tokAt(3), tok->tokAt(6));

// goto the ";"
tok = tok->tokAt(5);

// insert "var=0;"
tok->insertToken(";");
tok->insertToken("0");
tok->insertToken("=");
tok->insertToken(varname);
tok->next()->varId(varid);
}
else if (Token::Match(tok, "; %var% = realloc ( 0 , %num% ) ;"))
{
const std::string varname(tok->next()->str());

tok = tok->tokAt(3);
// Change function name "realloc" to "malloc"
tok->str("malloc");

// delete "0 ,"
tok->next()->deleteNext();
tok->next()->deleteNext();
}
}

// Change initialisation of variable to assignment
simplifyInitVar();

Expand Down
4 changes: 4 additions & 0 deletions test/testsimplifytokens.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6004,6 +6004,10 @@ class TestSimplifyTokens : public TestFixture
{
ASSERT_EQUALS("; free ( p ) ; p = 0 ;",
tok("; p = realloc(p,0);"));
ASSERT_EQUALS("; p = malloc ( 100 ) ;",
tok("; p = realloc(0, 100);"));
ASSERT_EQUALS("; p = malloc ( 0 ) ;",
tok("; p = realloc(0, sizeof(char)*0);"));
}

void simplifyErrNoInWhile()
Expand Down