diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 8e894cdf8b3..f1257c80834 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -2014,6 +2014,12 @@ static void valueFlowForwardLifetime(Token * tok, const TokenList &tokenlist, Er } else if (tok->variable() && tok->variable()->scope()) { const Variable *var = tok->variable(); const Token *endOfVarScope = var->scope()->bodyEnd; + // Non-local variable: do not forward past the end of the current function + if (!var->isLocal() && !var->isArgument()) { + const Token* endOfFunction = ValueFlow::getEndOfExprScope(tok); + if (endOfFunction && (!endOfVarScope || precedes(endOfFunction, endOfVarScope))) + endOfVarScope = endOfFunction; + } std::list values = tok->values(); Token *nextExpression = nextAfterAstRightmostLeaf(parent); diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 1e953af1535..d1a4340e5b6 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -828,6 +828,14 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(true, testLifetimeOfX(code, 5, "a ;")); } + { + // lifetime of global array must not be forwarded into the next function + const char code[] = "int x[10];\n" + "void f() { int* p = x + 1; }\n" + "void g() { x[0] = 0; }\n"; + ASSERT_EQUALS(false, testLifetimeOfX(code, 3, "x [")); + } + { const char code[] = "void f() {\n" " std::vector v;\n"