Skip to content

Commit 05ff791

Browse files
danmardmcppcheckclaude
authored
Fix #15218 (ValueFlow: wrong lifetime values for non-local variables accross functions) (cppcheck-opensource#9014)
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: Daniel Marjamäki <daniel.marjamaki@cppcheck.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 42c9edd commit 05ff791

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
@@ -2014,6 +2014,12 @@ static void valueFlowForwardLifetime(Token * tok, const TokenList &tokenlist, Er
20142014
} else if (tok->variable() && tok->variable()->scope()) {
20152015
const Variable *var = tok->variable();
20162016
const Token *endOfVarScope = var->scope()->bodyEnd;
2017+
// Non-local variable: do not forward past the end of the current function
2018+
if (!var->isLocal() && !var->isArgument()) {
2019+
const Token* endOfFunction = ValueFlow::getEndOfExprScope(tok);
2020+
if (endOfFunction && (!endOfVarScope || precedes(endOfFunction, endOfVarScope)))
2021+
endOfVarScope = endOfFunction;
2022+
}
20172023

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

‎test/testvalueflow.cpp‎

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

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

0 commit comments

Comments
 (0)