Uninitialized variables: Fix false positives related to for loop

This commit is contained in:
Daniel Marjamäki 2011-12-27 08:18:05 +01:00
parent 5bac8eca37
commit fdb6ee2ad7
2 changed files with 32 additions and 7 deletions

View File

@ -1177,6 +1177,10 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const unsigned int
// for..
if (Token::simpleMatch(tok, "for (")) {
// is variable initialized in for-head (don't report errors yet)?
if (checkIfForWhileHead(tok->next(), varid, ispointer, true, false))
return true;
// goto the {
const Token *tok2 = tok->next()->link()->next();
@ -1187,9 +1191,10 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const unsigned int
if (possibleinit || init)
return true;
// is variable used / initialized in for-head
if (checkIfForWhileHead(tok->next(), varid, ispointer, suppressErrors, bool(number_of_if == 0)))
return true;
// is variable used in for-head?
if (!suppressErrors) {
checkIfForWhileHead(tok->next(), varid, ispointer, false, bool(number_of_if == 0));
}
}
// TODO: handle loops, try, etc
@ -1227,8 +1232,12 @@ bool CheckUninitVar::checkIfForWhileHead(const Token *startparanthesis, unsigned
const Token * const endpar = startparanthesis->link();
for (const Token *tok = startparanthesis->next(); tok && tok != endpar; tok = tok->next()) {
if (tok->varId() == varid) {
if (!suppressErrors && isVariableUsage(tok, ispointer))
uninitvarError(tok, tok->str());
if (isVariableUsage(tok, ispointer)) {
if (!suppressErrors)
uninitvarError(tok, tok->str());
else
continue;
}
return true;
}
if (Token::Match(tok, "sizeof|decltype|offsetof ("))

View File

@ -1846,6 +1846,14 @@ private:
"}");
ASSERT_EQUALS("", errout.str());
checkUninitVar2("int f() {\n"
" int i,x;\n"
" for (i=0;i<9;++i)\n"
" if (foo) break;\n"
" return x;\n"
"}\n");
TODO_ASSERT_EQUALS("error", "", errout.str());
// for, while
checkUninitVar2("void f() {\n"
" int x;\n"
@ -1866,11 +1874,19 @@ private:
checkUninitVar2("void f() {\n"
" int x;\n"
" for (int i = 0; i < 10; i += x) {\n"
" }\n"
" for (int i = 0; i < 10; i += x) { }\n"
"}\n");
ASSERT_EQUALS("[test.cpp:3]: (error) Uninitialized variable: x\n", errout.str());
checkUninitVar2("int f() {\n"
" int i;\n"
" for (i=0;i<9;++i)\n"
" if (foo()) goto out;\n"
"out:\n"
" return i;\n"
"}\n");
ASSERT_EQUALS("", errout.str());
// try
checkUninitVar2("void f() {\n"
" int i, *p = &i;\n"