From fdb6ee2ad7b5788decd0575db358da28d31c2285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Tue, 27 Dec 2011 08:18:05 +0100 Subject: [PATCH] Uninitialized variables: Fix false positives related to for loop --- lib/checkuninitvar.cpp | 19 ++++++++++++++----- test/testuninitvar.cpp | 20 ++++++++++++++++++-- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp index d88676efc..a9868c550 100644 --- a/lib/checkuninitvar.cpp +++ b/lib/checkuninitvar.cpp @@ -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 (")) diff --git a/test/testuninitvar.cpp b/test/testuninitvar.cpp index 22c691a9a..6ad330068 100644 --- a/test/testuninitvar.cpp +++ b/test/testuninitvar.cpp @@ -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"