Repository navigation
Partial fix for #15291 FN returnReference with cast - #9094
chrchr-github wants to merge 6 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.
| return false; | ||
| if (tok->valueType() && tok->valueType()->reference != Reference::None) | ||
| return isTemporary(op, library); | ||
| return true; |
There was a problem hiding this comment.
AI review
This return true also applies to casts to a pointer type. In isSameIteratorContainerExpression() (checkstl.cpp) the container expression is the cast itself, so the same C++ pointer cast now counts as a temporary container:
void f(void* p) { std::sort(static_cast<std::vector<int>*>(p)->begin(), static_cast<std::vector<int>*>(p)->end()); }The PR now reports Iterators to containers from different expressions 'static_cast<std::vector<int>*>(p)' and 'static_cast<std::vector<int>*>(p)' are used together. [mismatchingContainerExpression]. Base gives no warning, and reinterpret_cast and const_cast behave the same way. The pointer itself is a prvalue, but the object it points to is not a temporary. One fix is to keep the old behaviour for pointer results, for example if (tok->valueType() && tok->valueType()->pointer > 0) return false; or recurse into the operand. A regression test in teststl would cover it.
There was a problem hiding this comment.
See https://trac.cppcheck.net/ticket/15302
Pointers can also be temporaries: int* const& f() { return (int*)0; }
No description provided.