From ca5fab8219d12dbae633904c7bddaf9a941f1bdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Wed, 19 May 2021 21:12:11 +0200 Subject: [PATCH] Uninitialized variables; Fixed false positive in range for loop --- lib/checkuninitvar.cpp | 13 +++++++++---- test/testuninitvar.cpp | 6 ++++++ 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp index 1f80810dc..cba0f56fa 100644 --- a/lib/checkuninitvar.cpp +++ b/lib/checkuninitvar.cpp @@ -1138,12 +1138,17 @@ const Token* CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, return nullptr; } - // LHS in range for loop: + // range for loop if (Token::simpleMatch(valueExpr->astParent(), ":") && - astIsLhs(valueExpr) && valueExpr->astParent()->astParent() && - Token::simpleMatch(valueExpr->astParent()->astParent()->previous(), "for (")) - return nullptr; + Token::simpleMatch(valueExpr->astParent()->astParent()->previous(), "for (")) { + if (astIsLhs(valueExpr)) + return nullptr; + // Taking value by reference? + const Token *lhs = valueExpr->astParent()->astOperand1(); + if (lhs && lhs->variable() && lhs->variable()->nameToken() == lhs && lhs->variable()->isReference()) + return nullptr; + } // Stream read/write // FIXME this code is a hack!! diff --git a/test/testuninitvar.cpp b/test/testuninitvar.cpp index 044efca34..a971a9e09 100644 --- a/test/testuninitvar.cpp +++ b/test/testuninitvar.cpp @@ -4164,6 +4164,12 @@ private: " for (item: itemList) {}\n" "}"); ASSERT_EQUALS("", errout.str()); + + checkUninitVar("void f() {\n" + " int buf[10];\n" + " for (int &i: buf) { i = 0; }\n" + "}"); + ASSERT_EQUALS("", errout.str()); } void uninitvar_static() { // #8734