Skip to content

Commit b60f304

Browse files
dmcppcheckclaude
andcommitted
valueFlowForwardLifetime: do not forward lifetime of non-local variable past end of function
For a global variable the scope body end is null so the lifetime was forwarded through the rest of the file, into unrelated functions. colobot restext.cpp: ValueFlow 615s => 5s. In 10000 Debian packages (--check-level=exhaustive) this removes 11 false positives (danglingLifetime, objectIndex) and adds no warnings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 9074c47 commit b60f304

2 files changed

Lines changed: 14 additions & 0 deletions

File tree

‎lib/valueflow.cpp‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2007,6 +2007,12 @@ static void valueFlowForwardLifetime(Token * tok, const TokenList &tokenlist, Er
20072007
} else if (tok->variable() && tok->variable()->scope()) {
20082008
const Variable *var = tok->variable();
20092009
const Token *endOfVarScope = var->scope()->bodyEnd;
2010+
// Non-local variable: do not forward past the end of the current function
2011+
if (!var->isLocal() && !var->isArgument()) {
2012+
const Token* endOfFunction = ValueFlow::getEndOfExprScope(tok);
2013+
if (endOfFunction && (!endOfVarScope || precedes(endOfFunction, endOfVarScope)))
2014+
endOfVarScope = endOfFunction;
2015+
}
20102016

20112017
std::list<ValueFlow::Value> values = tok->values();
20122018
Token *nextExpression = nextAfterAstRightmostLeaf(parent);

‎test/testvalueflow.cpp‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -826,6 +826,14 @@ class TestValueFlow : public TestFixture {
826826
ASSERT_EQUALS(true, testLifetimeOfX(code, 5, "a ;"));
827827
}
828828

829+
{
830+
// lifetime of global array must not be forwarded into the next function
831+
const char code[] = "int x[10];\n"
832+
"void f() { int* p = x + 1; }\n"
833+
"void g() { x[0] = 0; }\n";
834+
ASSERT_EQUALS(false, testLifetimeOfX(code, 3, "x ["));
835+
}
836+
829837
{
830838
const char code[] = "void f() {\n"
831839
" std::vector<int> v;\n"

0 commit comments

Comments
 (0)