Uninitialized variables: Fixed false positives when goto is simplified and inner condition is known to be true/false

This commit is contained in:
Daniel Marjamäki 2012-02-06 07:32:29 +01:00
parent 548a43fc49
commit d6a887e1f9
2 changed files with 22 additions and 0 deletions

View File

@ -1088,6 +1088,9 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const unsigned int
unsigned int number_of_if = 0; unsigned int number_of_if = 0;
// variables that are known to be non-zero
std::set<unsigned int> notzero;
for (; tok; tok = tok->next()) { for (; tok; tok = tok->next()) {
// End of scope.. // End of scope..
if (tok->str() == "}") { if (tok->str() == "}") {
@ -1109,12 +1112,20 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const unsigned int
continue; continue;
} }
// assignment with nonzero constant..
if (Token::Match(tok, "[;{}] %var% = - %var% ;") && tok->next()->varId() > 0)
notzero.insert(tok->next()->varId());
// Inner scope.. // Inner scope..
if (Token::simpleMatch(tok, "if (")) { if (Token::simpleMatch(tok, "if (")) {
// initialization / usage in condition.. // initialization / usage in condition..
if (checkIfForWhileHead(tok->next(), varid, ispointer, suppressErrors, bool(number_of_if == 0))) if (checkIfForWhileHead(tok->next(), varid, ispointer, suppressErrors, bool(number_of_if == 0)))
return true; return true;
// checking if a not-zero variable is zero => bail out
if (Token::Match(tok, "if ( %var% )") && notzero.find(tok->tokAt(2)->varId()) != notzero.end())
return true; // this scope is not fully analysed => return true
// goto the { // goto the {
tok = tok->next()->link()->next(); tok = tok->next()->link()->next();

View File

@ -1889,6 +1889,17 @@ private:
"}\n"); "}\n");
TODO_ASSERT_EQUALS("error", "", errout.str()); TODO_ASSERT_EQUALS("error", "", errout.str());
// if goto is simplified there might be conditions that are always true
checkUninitVar2("void f() {\n"
" int i;\n"
" if (x) {\n"
" int y = -ENOMEM;\n"
" if (y != 0) return;\n"
" i++;\n"
" }\n"
"}\n");
ASSERT_EQUALS("", errout.str());
// for, while // for, while
checkUninitVar2("void f() {\n" checkUninitVar2("void f() {\n"
" int x;\n" " int x;\n"