Permalink
Browse files

Uninitialized variables: Fixed false positives when goto is simplifie…

…d and inner condition is known to be true/false
  • Loading branch information...
1 parent 548a43f commit d6a887e1f9549a26062c5ffe99f650f5ff3ccc34 @danmar committed Feb 6, 2012
Showing with 22 additions and 0 deletions.
  1. +11 −0 lib/checkuninitvar.cpp
  2. +11 −0 test/testuninitvar.cpp
View
@@ -1088,6 +1088,9 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const unsigned int
unsigned int number_of_if = 0;
+ // variables that are known to be non-zero
+ std::set<unsigned int> notzero;
+
for (; tok; tok = tok->next()) {
// End of scope..
if (tok->str() == "}") {
@@ -1109,12 +1112,20 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const unsigned int
continue;
}
+ // assignment with nonzero constant..
+ if (Token::Match(tok, "[;{}] %var% = - %var% ;") && tok->next()->varId() > 0)
+ notzero.insert(tok->next()->varId());
+
// Inner scope..
if (Token::simpleMatch(tok, "if (")) {
// initialization / usage in condition..
if (checkIfForWhileHead(tok->next(), varid, ispointer, suppressErrors, bool(number_of_if == 0)))
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 {
tok = tok->next()->link()->next();
View
@@ -1889,6 +1889,17 @@ class TestUninitVar : public TestFixture {
"}\n");
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
checkUninitVar2("void f() {\n"
" int x;\n"

0 comments on commit d6a887e

Please sign in to comment.