Skip to content

Commit fbff666

Browse files
chrchr-githubweb-flow
authored andcommitted
Fix #11125 FP unreadVariable with loop over array (cppcheck-opensource#8357)
1 parent 90e8c7c commit fbff666

2 files changed

Lines changed: 27 additions & 1 deletion

File tree

lib/fwdanalysis.cpp

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,16 @@ FwdAnalysis::Result FwdAnalysis::checkRecursive(const Token *expr, const Token *
410410
return Result(Result::Type::NONE);
411411
}
412412

413+
static bool isSimpleIndexExpression(const Token* tok)
414+
{
415+
const Token* idx = tok->astOperand2();
416+
if (!idx)
417+
return false;
418+
if (idx->isIncDecOp())
419+
idx = idx->astOperand1();
420+
return idx->variable() && idx->variable()->scope() == tok->scope();
421+
}
422+
413423
std::set<nonneg int> FwdAnalysis::getExprVarIds(const Token* expr, bool* localOut, bool* unknownVarIdOut) const
414424
{
415425
// all variable ids in expr.
@@ -418,7 +428,7 @@ std::set<nonneg int> FwdAnalysis::getExprVarIds(const Token* expr, bool* localOu
418428
bool unknownVarId = false;
419429
visitAstNodes(expr,
420430
[&](const Token *tok) {
421-
if (tok->str() == "[" && mWhat == What::UnusedValue)
431+
if (tok->str() == "[" && mWhat == What::UnusedValue && isSimpleIndexExpression(tok))
422432
return ChildrenToVisit::op1;
423433
if (tok->varId() == 0 && tok->isName() && tok->strAt(-1) != ".") {
424434
// unknown variable

test/testunusedvar.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5813,6 +5813,22 @@ class TestUnusedVar : public TestFixture {
58135813
" {}\n"
58145814
"}");
58155815
ASSERT_EQUALS("", errout_str());
5816+
5817+
functionVariableUsage("void f(const int* b, int x) {\n" // #11125
5818+
" int a[6];\n"
5819+
" int i = 0;\n"
5820+
" for (int j = 0; j < 6; ++j) {\n"
5821+
" if (b[j] != 0) {\n"
5822+
" a[i] = j;\n"
5823+
" ++i;\n"
5824+
" }\n"
5825+
" }\n"
5826+
" if (i > 1) {\n"
5827+
" a[i] = a[0];\n"
5828+
" (void)a[x];\n"
5829+
" }\n"
5830+
"}\n");
5831+
ASSERT_EQUALS("", errout_str());
58165832
}
58175833

58185834
void localvarForEach() { // #4155 - foreach

0 commit comments

Comments
 (0)