Repository navigation
Partial fix for #15291 FN returnReference with cast - #9094
chrchr-github wants to merge 12 commits into
Conversation
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The new loop removes every cast, including casts to a value type such as (int)i, static_cast<int>(i) and (const A)a. Those casts create a prvalue temporary, so a function returning const int& now gets returnReference ("Reference to local variable returned") instead of the right diagnosis, which is a reference to a temporary. Base reports nothing for these cases, so the code is still buggy, but the message names the wrong cause. The reference-cast case that the PR targets works for C-style, static_cast, reinterpret_cast and const_cast, for nested casts and for templates, with no false positives for references to globals, statics or references. Apart from this I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Redundant condition 'varTok' or possible null pointer dereference | @github-advanced-security[bot] | lib/checkautovariables.cpp:584 |
✅ Fixed |
| 2 | Value casts are stripped too, so a returned temporary is reported as a reference to a local variable | AI review | lib/checkautovariables.cpp:584 |
🆕 New |
@chrchr-github, please fix, resolve or reply to the open and new comments: #2.
Testing
I built cppcheck and testrunner in pr/ and cppcheck in base/. ./testrunner TestAutoVariables passed: 109 tests, 0 failures, 4 todos.
Reference casts. I ran pr/cppcheck -q --enable=all --inconclusive a.cpp on these:
(int&)i,static_cast<int&>(i),reinterpret_cast<int&>(i),const_cast<int&>(i),(long&)i,(int&)(i),(const int&)(int&)iand(T&)tin a template are now reported asreturnReference.(int&)gfor a global,(int&)xfor a static,(int&)rfor a reference parameter and(int&)*pare not reported, which is correct.(int&)s.mand(int&)(i, i)are still not reported. Neither base nor PR reports them.
Value casts. These now get the wrong message. Test file b.cpp:
const int& f1(int i) { return (int)i; }
const long& f2(int i) { return (long)i; }
const int& f3(int i) { return static_cast<int>(i); }
const int& f4(int i) { return int(i); }
struct A { int x; };
const A& f5(A a) { return (const A)a; }Command: cppcheck -q --enable=warning,style --inconclusive b.cpp
PR output:
b.cpp:1:31: error: Reference to local variable returned. [returnReference]
b.cpp:2:32: error: Reference to local variable returned. [returnReference]
b.cpp:3:47: error: Reference to local variable returned. [returnReference]
b.cpp:4:34: error: Reference to temporary returned. [returnTempReference]
b.cpp:6:27: error: Reference to local variable returned. [returnReference]
Base reports only line 4, as returnTempReference. Lines 1, 2, 3 and 6 return a reference to a temporary made by the cast, not to the local i or a. The functional cast on line 4 is classified correctly, so the cast forms are now reported inconsistently.
Rvalue-reference cast. const int& f5(int i) { return (int&&)i; } is now reported as returnReference; base reports nothing.
There were no crashes on the edge cases I tried.
Automated review of 85101ba by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. The problem from the earlier review is fixed: value casts such as (int)i, static_cast<int>(i) and (const A)a returned as const T& are now reported as returnTempReference, and reference casts of locals are reported as returnReference. The change to isTemporary() also gives some new true positives in other checks, such as ((std::vector<int>)v).begin() (danglingTemporaryLifetime) and ((std::string)p).c_str() returned (returnDanglingLifetime). I found no false positives from pointer casts or from casts to unknown types. No test covers those new checks.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Value casts are stripped too, so a returned temporary is reported as a reference to a local variable | AI review | lib/checkautovariables.cpp:584 |
✅ Fixed |
Testing
I built cppcheck and testrunner in pr/ and cppcheck in base/. ./testrunner TestAutoVariables TestAstUtils TestValueFlow TestOther ran 468 tests with 0 failures.
Earlier finding (C3): I re-ran the value-cast file from the earlier review with cppcheck -q --enable=warning,style --inconclusive b2.cpp. The PR now gives returnTempReference for (int)i, (long)i, static_cast<int>(i), int(i) and (const A)a. (int&&)i and static_cast<int&&>(i) are reported as returnReference. That is correct, because the result is an xvalue that refers to the local.
Reference casts: these are reported correctly:
(const std::string&)sof a local(int&)(int&)i(const int&)iwhereiisunsignedint& r = (int&)i; return r;const int& r = (int)l; return r;, reported as a temporary&(const int&)(int)l, reported asreturnDanglingLifetime
There are no reports for references to statics, to reference parameters or through *(A*)p.
Possible side effects of the isTemporary change: a cast whose result is not a reference now counts as a temporary, also when its type is unknown. I wrote small files to look for false positives:
- pointer casts followed by
->:((S*)p)->v.begin(),static_cast<S*>(p)->v.begin(),((S*)p)->s.c_str(),&((S*)p)->a[0],string_viewfrom((S*)p)->s (*(S*)p).v.begin()- casts to unknown types, by value and by reference:
(Vec)v,(Vec&)v,(const Derived&)b - references bound through such casts and then returned
The PR's output was the same as base's, except for two new true positives:
((std::vector<int>)v).begin()givesdanglingTemporaryLifetime- returning
((std::string)p).c_str()givesreturnDanglingLifetime
Regression check: I ran PR and base with --enable=all --inconclusive on test/cfg/{std,qt,windows,wxwidgets,boost}.cpp and samples/*/bad.c*. The output was identical, 2804 lines from each.
There were no crashes or hangs.
Automated review of e566e28 by Claude. The pull request was built and tested locally.
|
Test results for commit e566e28 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9094/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. The two earlier findings are fixed in this version:
- the null-pointer warning from the code scanner (C1)
- value casts reported as
returnReference(C3)
The new compound-literal check in isTemporary() works. &(int){i} in C and (int[]){i, 2} assigned to a pointer give no warnings. For casts of locals to reference types, the PR reports returnReference. Value casts in all their forms give returnTempReference. I found no false positives from pointer casts, from casts to unknown reference types or from casts of reference parameters.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Redundant condition 'varTok' or possible null pointer dereference | @github-advanced-security[bot] | lib/checkautovariables.cpp:584 |
✅ Fixed |
| 2 | Value casts stripped too, so a returned temporary is reported as a reference to a local | AI review | lib/checkautovariables.cpp:584 |
✅ Fixed |
Testing
I built cppcheck and testrunner in pr/ and cppcheck in base/. ./testrunner TestAutoVariables TestAstUtils TestValueFlow TestOther TestStl ran 591 tests with 0 failures and 70 todos.
I ran cppcheck -q --enable=warning,style --inconclusive from base and from the PR on scratch files:
- Reference and value casts:
static_cast<int&>(i)and(int&)(i)of a local givereturnReference.static_cast<int>(i)and(int)ireturned asconst int&givereturnTempReference.(const int&)(char&)igivesreturnReference.((std::string)p).c_str()andstatic_cast<std::string>(p).c_str()returned givereturnDanglingLifetime. These are new true positives.
- C compound literals and pointer casts: I tried
((struct S*)p)->buf,&((struct S*)p)->a[0],(int[]){i,2}assigned to a pointer and then returned or used, and&(struct S){...}. Base and PR gave the same output, with no new warnings. The same file compiled as C++ gave no warnings either. - Casts to unknown types: I tried
static_cast,dynamic_cast,reinterpret_castand C-style casts toUnknown&,const Str&andconst Vec&, then used.begin(),.c_str(),string_viewor returned them. Base and PR gave the same output, with no new errors. - Regression runs: I ran both versions with
--enable=all --inconclusiveontest/cfg/{std.c,std.cpp,posix.c,gtk.c,qt.cpp,windows.cpp}andsamples. Both gave the same 14141 lines. I also ran both onexternals/tinyxml2,simplecpp.cpp,lib/token.cppandlib/astutils.cpp, and both gave the same 120 lines.
There were no crashes or hangs. I could not see the 9 regressions that the PR test runner (C5) listed for commit e566e28, so I could not check whether the later commit fixes them.
Automated review of d2794ed by Claude. The pull request was built and tested locally.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
New false positive. isTemporary() now returns true for every cast whose result is not a reference, and that includes pointer casts. When the same C++ pointer cast (static_cast, reinterpret_cast or const_cast) supplies both iterators, the PR now reports mismatchingContainerExpression: std::sort(static_cast<std::vector<int>*>(p)->begin(), static_cast<std::vector<int>*>(p)->end()). Base gives no warning for this code. A cast to a pointer type gives a temporary pointer, but the container it points to is not a temporary, so callers that ask whether the container is a temporary get the wrong answer.
Otherwise the reference-cast and value-cast cases work as intended. The PR also gives new true positives: returning (const std::string&)mk() or (const int&)(i + 1), and int* const& f(int* p) { return (int*)p; }. Apart from the pointer-cast issue I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Redundant condition 'varTok' or possible null pointer dereference | @github-advanced-security[bot] | lib/checkautovariables.cpp:584 |
✅ Fixed |
| 2 | Value casts stripped too, so a returned temporary is reported as a reference to a local | AI review | lib/checkautovariables.cpp:584 |
✅ Fixed |
| 3 | Pointer casts now count as temporaries, giving a new mismatchingContainerExpression false positive for C++ pointer casts | AI review | lib/astutils.cpp:455 |
🆕 New |
@chrchr-github, please fix, resolve or reply to the open and new comments: #3.
Testing
I built cppcheck and testrunner in pr/ and cppcheck in base/. ./testrunner TestAutoVariables TestAstUtils passed: 120 tests, 0 failures, 5 todos.
New false positive with C++ pointer casts (scratch/e.cpp):
#include <vector>
#include <algorithm>
void f2(void* p) { std::sort(static_cast<std::vector<int>*>(p)->begin(), static_cast<std::vector<int>*>(p)->end()); }
void f3(std::vector<int>& v) { std::sort(static_cast<std::vector<int>&>(v).begin(), static_cast<std::vector<int>&>(v).end()); }
void f7(void* p) { std::sort(reinterpret_cast<std::vector<int>*>(p)->begin(), reinterpret_cast<std::vector<int>*>(p)->end()); }
void f8(const std::vector<int>* p) { std::sort(const_cast<std::vector<int>*>(p)->begin(), const_cast<std::vector<int>*>(p)->end()); }Command: cppcheck -q --library=std --enable=warning,style --inconclusive e.cpp
Base: no warnings about iterators. PR:
e.cpp:5:60: warning: Iterators to containers from different expressions 'static_cast<std::vector<int>*>(p)' and 'static_cast<std::vector<int>*>(p)' are used together. [mismatchingContainerExpression]
e.cpp:7:65: warning: ... 'reinterpret_cast<std::vector<int>*>(p)' ... [mismatchingContainerExpression]
e.cpp:8:77: warning: ... 'const_cast<std::vector<int>*>(p)' ... [mismatchingContainerExpression]
Line numbers count the two struct lines of the full test file. The C-style form ((std::vector<int>*)p)->begin() already gives this false positive in base, so it is not new.
Other cases where the PR's result differs from base, all true positives:
return (const std::string&)mk();andreturn (const std::string&)std::string("a");→returnTempReferencereturn (const int&)(i + 1);→returnTempReference((const std::string&)mk()).c_str()used later →danglingTemporaryLifetimeint* const& f8(int* p) { return (int*)p; }→returnTempReference
No change from base:
- casts to unknown reference types such as
(Foo&)b,(MyStr&)band(const T&)bin a template string_view/spanvalue casts followed by.data(), where base already hasstlcstrfalse positives
Automated review of d2794ed by Claude. The pull request was built and tested locally.
|
Test results for commit d2794ed (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9094/ Posted automatically by the cppcheck PR test runner. +N: warnings only with this PR, -N: warnings only with main. The AI review is written by Claude and can be wrong. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
New false-negative regression: the latest commits added var->valueType() && var->valueType()->type != ValueType::UNKNOWN_TYPE to the returnReference condition. That condition applies to every returned local, not only to locals reached through a cast. So returnReference is now lost when the local's type is unknown to cppcheck: undeclared classes, forward-declared classes, template parameter types, pointers to unknown types and library types when the library is not loaded (QString without --library=qt). Base reports all of these. In the cases I tested, types that cppcheck knows (int, a defined struct, std::string, std::vector) are still reported. No existing test covers the lost cases, so testrunner still passes. Apart from this I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Value casts stripped too, so a returned temporary is reported as a reference to a local | AI review | lib/checkautovariables.cpp:584 |
✅ Fixed |
| 2 | Pointer casts now count as temporaries, giving a mismatchingContainerExpression false positive | AI review | lib/astutils.cpp:455 |
🎫 Ticket #15302 |
| 3 | UNKNOWN_TYPE check drops returnReference for every local of unknown type, not only for casts | AI review | lib/checkautovariables.cpp:587 |
🆕 New (false negative) |
@chrchr-github, please fix, resolve or reply to the open and new comments: #3.
For #3 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
I built cppcheck and testrunner in pr/ and cppcheck in base/. ./testrunner TestAutoVariables TestAstUtils TestStl ran 243 tests: 0 failures, 20 todos.
Regression: lost returnReference for locals of unknown type
b.cpp:
struct A { int x; };
A& g1() { A a; return a; }
Foo*& g2() { Foo* p = nullptr; return p; }
template<class T> struct W { T& get() { T t; return t; } };
class Bar; Bar& g3(Bar b) { return b; }
QString& g4() { QString s; return s; }Command: cppcheck -q --enable=warning --inconclusive b.cpp
Base:
b.cpp:2:23: error: Reference to local variable returned. [returnReference]
b.cpp:3:39: error: Reference to local variable returned. [returnReference]
b.cpp:4:53: error: Reference to local variable returned. [returnReference]
b.cpp:5:36: error: Reference to local variable returned. [returnReference]
b.cpp:6:35: error: Reference to local variable returned. [returnReference]
PR:
b.cpp:2:23: error: Reference to local variable returned. [returnReference]
With --library=qt, the PR still reports line 6, but lines 3, 4 and 5 are still missing.
A second file gave the same result. For Foo& f1() { Foo x; return x; } and template<class T> T& f3() { T t; return t; }, base reports returnReference and the PR reports nothing. In that file, int, std::string and std::vector<int> locals are still reported.
Automated review of a325e00 by Claude. The pull request was built and tested locally.
| while (varTok->isCast() && varTok->valueType() && varTok->valueType()->reference != Reference::None) | ||
| varTok = varTok->isBinaryOp() ? varTok->astOperand2() : varTok->astOperand1(); | ||
| const Variable* var = varTok->variable(); | ||
| if (var && !var->isGlobal() && !var->isStatic() && !var->isReference() && !var->isRValueReference() && var->valueType() && var->valueType()->type != ValueType::UNKNOWN_TYPE && |
There was a problem hiding this comment.
AI review
The new check var->valueType() && var->valueType()->type != ValueType::UNKNOWN_TYPE applies to every returned local, including locals that are not reached through a cast. This loses true positives that base reports:
Foo& f1() { Foo x; return x; } // undeclared class
template<class T> T& f3() { T t; return t; } // template parameter type
class Bar; Bar& g3(Bar b) { return b; } // forward-declared class
Foo*& g2() { Foo* p = nullptr; return p; } // pointer to unknown type
QString& g4() { QString s; return s; } // without --library=qtBase reports returnReference for all of these. The PR reports none of them.
If the check is only meant to suppress the const_cast<T&>(u) case from the new test, you could apply it only when a cast was stripped (varTok != lt.token). A test with an unknown-type local, such as Foo& f() { Foo x; return x; }, would catch this regression.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. The false negative from C11/C12 is only partly fixed. The new condition in checkVarLifetimeScope now keeps two cases: pointers, and locals whose Type is the same as the function's return type. Every other local of a type that cppcheck does not know still loses returnReference, and nobody has answered that comment. The lost cases include an undeclared class (Foo& f() { Foo x; return x; }), template parameter types, QString without the qt library, a forward-declared derived type returned as its base, auto& returns and array elements. Base reports all of these. The value-cast problem (C2/C3) is fixed. The pointer-cast false positive (C8) has a ticket.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Value casts stripped too, so a returned temporary is reported as a reference to a local | AI review | general | ✅ Fixed |
| 2 | Value casts stripped too, so a returned temporary is reported as a reference to a local | AI review | lib/checkautovariables.cpp:584 |
✅ Fixed |
| 3 | Pointer casts count as temporaries, giving a mismatchingContainerExpression false positive | AI review | general | 🎫 Ticket #15302 |
| 4 | Pointer casts count as temporaries, giving a mismatchingContainerExpression false positive | AI review | lib/astutils.cpp:455 |
🎫 Ticket #15302 |
| 5 | UNKNOWN_TYPE check drops returnReference for locals of unknown type, not only for casts | AI review | general | |
| 6 | UNKNOWN_TYPE check drops returnReference for locals of unknown type, not only for casts | AI review | lib/checkautovariables.cpp:587 |
@chrchr-github, please fix, resolve or reply to the open and new comments: #5, #6.
For #5 and #6 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
I built cppcheck and testrunner in pr/ and cppcheck in base/. ./testrunner TestAutoVariables TestAstUtils TestStl ran 243 tests: 0 failures, 20 todos.
I checked the C12 regression again on the current head with scratch/a.cpp:
Foo& f1() { Foo x; return x; }
template<class T> struct W { T& get() { T t; return t; } };
template<class T> T& f3() { T t; return t; }
QString& g4() { QString s; return s; }
class Base; class Derived;
Base& f5() { Derived d; return d; }
struct B2 {}; struct D2 : B2 {};
B2& f6() { D2 d; return d; }
const Foo& f7(Foo x) { return x; }
std::string& f8() { std::string s; return s; }
auto& f9() { Foo x; return x; }
Foo& f10() { Foo x[3]; return x[0]; }Command: cppcheck -q --enable=warning --inconclusive a.cpp
- Base:
returnReferenceon all 10 functions. - PR: only on lines 8 and 10 (
f6andf8).
So the cases in C12 are still lost: undeclared class, template parameter and QString. So are the related cases on lines 6, 9, 11 and 12 (f5, f7, f9, f10).
Automated review of 7d533c8 by Claude. The pull request was built and tested locally.
|
A warning for e.g. |
No description provided.