From a6f25114b0c181b9c5920e4e9bf2f06b334cc5d4 Mon Sep 17 00:00:00 2001 From: chrchr-github Date: Mon, 30 Nov 2026 18:35:02 +0100 Subject: [PATCH 1/2] Fix #15291 FN returnReference with cast --- lib/checkautovariables.cpp | 5 ++++- test/testautovariables.cpp | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/checkautovariables.cpp b/lib/checkautovariables.cpp index de70772a279..b29b5ecb9a2 100644 --- a/lib/checkautovariables.cpp +++ b/lib/checkautovariables.cpp @@ -580,7 +580,10 @@ void CheckAutoVariablesImpl::checkVarLifetimeScope(const Token * start, const To for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(tok, mSettings, true)) { if (!printInconclusive && lt.inconclusive) continue; - const Variable* var = lt.token->variable(); + const Token* varTok = lt.token; + while (varTok && varTok->isCast()) + varTok = varTok->isBinaryOp() ? varTok->astOperand2() : varTok->astOperand1(); + const Variable* var = varTok->variable(); if (var && !var->isGlobal() && !var->isStatic() && !var->isReference() && !var->isRValueReference() && isInScope(var->nameToken(), tok->scope())) { errorReturnReference(tok, lt.errorPath, lt.inconclusive); diff --git a/test/testautovariables.cpp b/test/testautovariables.cpp index d5ab5855c32..97463676cd8 100644 --- a/test/testautovariables.cpp +++ b/test/testautovariables.cpp @@ -134,6 +134,7 @@ class TestAutoVariables : public TestFixture { TEST_CASE(returnReference28); TEST_CASE(returnReference29); TEST_CASE(returnReference30); // #15094 + TEST_CASE(returnReference31); TEST_CASE(returnReferenceFunction); TEST_CASE(returnReferenceContainer); TEST_CASE(returnReferenceLiteral); @@ -1790,6 +1791,14 @@ class TestAutoVariables : public TestFixture { ASSERT_EQUALS("", errout_str()); } + void returnReference31() // #15291 + { + check("int& g(int i) {\n" + " return (int&)i;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:12]: (error) Reference to local variable returned. [returnReference]\n", errout_str()); + } + void returnReferenceFunction() { check("int& f(int& a) {\n" " return a;\n" From 85101baa0e7fd73cc2e55ba45bb9034b4d2ca939 Mon Sep 17 00:00:00 2001 From: chrchr-github Date: Mon, 30 Nov 2026 18:40:33 +0100 Subject: [PATCH 2/2] Fix --- lib/checkautovariables.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/checkautovariables.cpp b/lib/checkautovariables.cpp index b29b5ecb9a2..5996b5f4f3f 100644 --- a/lib/checkautovariables.cpp +++ b/lib/checkautovariables.cpp @@ -581,7 +581,7 @@ void CheckAutoVariablesImpl::checkVarLifetimeScope(const Token * start, const To if (!printInconclusive && lt.inconclusive) continue; const Token* varTok = lt.token; - while (varTok && varTok->isCast()) + while (varTok->isCast()) varTok = varTok->isBinaryOp() ? varTok->astOperand2() : varTok->astOperand1(); const Variable* var = varTok->variable(); if (var && !var->isGlobal() && !var->isStatic() && !var->isReference() && !var->isRValueReference() &&