Repository navigation
Fix #5459 (Detect endless for loops) - #9038
willgarvin wants to merge 10 commits into
Conversation
…oops) Fix cppcheck-opensource#5459 Detect Endless For Loops
…5459-(Detect-Endless-For-Loops)
Co-authored-by: Cursor <cursoragent@cursor.com>
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found several false positives that I reproduced. The new missingForLoopIncrement warning (severity warning) fires on loops that do terminate, in three cases:
- The step clause updates the variable through a call, like
inc(&i),std::advance(it, 1)ors.step(i).stepUpdatesVaronly looks for++/--/assignment operators, andfindExpressionChangedonly searches the body. - The loop condition depends on something else that changes, like
i < nwithn--in the body,i != get(), ori < *pwithvolatile int *p. The check only asks whether the loop variable changes. - The body ends the program by calling a noreturn function, like
exit(1)or a[[noreturn]]function.hasForLoopExitonly recognisesgoto,return,throwandbreak.
The tests the PR adds don't cover any of these cases.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Step clause that updates the variable through a call gives a false positive | AI review | lib/checkother.cpp:5010 |
🆕 New |
| 2 | Other operands of the condition can change, e.g. i < n with n-- in the body |
AI review | lib/checkother.cpp:5013 |
🆕 New |
| 3 | noreturn calls (exit, abort, [[noreturn]] functions) are not counted as a loop exit | AI review | lib/checkother.cpp:4940 |
🆕 New |
@willgarvin, please fix, resolve or reply to the open and new comments: #1, #2, #3.
Testing
I built cppcheck and testrunner in /work/pr.
./testrunner TestOther: 0 tests failed.pytest other_test.py -k active_unusedfunction: 4 passed.
I ran ./cppcheck -q --enable=warning --library=std <file> on test files I wrote. Each of the following reports warning: The loop variable 'i' (or 'it') is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement], and in each case the warning is false. I didn't build base/: the check is new, so base can't report it.
// t1.cpp – step clause updates i through a call
void inc(int* p);
void f1(int n) { for (int i = 0; i < n; inc(&i)) {} }
// t2.cpp
#include <iterator>
#include <list>
void f2(std::list<int>& l) { for (auto it = l.begin(); it != l.end(); std::advance(it, 1)) {} }
// t7.cpp
struct S { void step(int& i); };
void f7(S& s, int n) { for (int i = 0; i < n; s.step(i)) {} }
// t14.cpp – lambda in step
void f14(int n) { for (int i = 0; i < n; ([&]{ i++; })()) {} }// t3.cpp – the other operand of the condition changes
void use(int);
void f3(int n) { for (int i = 0; i < n;) { use(i); n--; } }
// t5.cpp
int get();
void f5() { for (int i = 0; i != get();) {} }
// t8.cpp
void f8(volatile int *p) { for (int i = 0; i < *p;) {} }// t4.c – noreturn call ends the program
#include <stdlib.h>
void use(int);
void f4(int n) { for (int i = 0; i < n;) { use(i); exit(1); } }
// t10.cpp: same with a user [[noreturn]] void fail(); in the bodyOutput, for example: t3.cpp:3:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement].
These cases behave correctly:
- A lambda in the body that changes
iby reference: no warning. int *p = &i; *p += 1;in the body: no warning.- A condition joined with
&&: no warning. - A loop whose body only does
continue: warning, and that loop really is endless.
Automated review of d4960e1 by Claude. The pull request was built and tested locally.
|
Test results for commit d4960e1 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9038/ 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. |
|
Addressed review comments. Ready for another look. |
Co-authored-by: Cursor <cursoragent@cursor.com>
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The fixes for the earlier review comments work: calls in the step, a changing bound and noreturn calls are now handled. I found one new class of false positive. The check still warns when the loop variable itself can be changed outside the code it sees:
- a
volatilecontrol variable whose address was passed out before the loop - a
std::atomic<int>that a thread captured by reference - a variable whose address was stored in a global pointer before the loop
The bound is now checked for volatile reads, but the control variable is not checked for volatile, atomic or address-taken. Apart from that, I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | Step clause that updates the variable through a call gives a false positive | AI review | lib/checkother.cpp:5010 |
✅ Fixed |
| 2 | Other operand of the condition can change (n--, get(), volatile *p) | AI review | lib/checkother.cpp:5079 |
✅ Fixed |
| 3 | noreturn calls (exit, abort, [[noreturn]]) not counted as a loop exit | AI review | lib/checkother.cpp:4971 |
✅ Fixed |
| 4 | Volatile/atomic or address-escaped control variable gives a false positive | AI review | lib/checkother.cpp:5040 |
🆕 New |
@willgarvin, please fix, resolve or reply to the open and new comments: #4.
Testing
Build and tests
- I built
cppcheckandtestrunnerin /work/pr. ./testrunner TestOther: 256 tests, 0 failed.pytest other_test.py -k active_unusedfunction: 4 passed.- I didn't build base/: the check is new, so base can't report it.
False positives (../pr/cppcheck -q --enable=warning --library=std <file>)
// a2.c – volatile control variable; its address escapes before the loop
void register_flag(volatile int *p);
void f2(void) {
volatile int done;
register_flag(&done);
for (done = 0; done == 0;) {}
}a2.c:5:5: warning: The loop variable 'done' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
// a1.cpp – atomic changed by another thread
#include <atomic>
#include <thread>
void f1() {
std::atomic<int> i;
std::thread t([&]{ i = 10; });
for (i = 0; i < 10;) {}
t.join();
}a1.cpp:6:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
// a4.c – address stored in a global pointer, then changed through a call
int *g;
void tick(void) { (*g)++; }
void f4(int n) { int i; g = &i; for (i = 0; i < n;) tick(); }a4.c:3:... warning: The loop variable 'i' is not updated in this for-loop ... [missingForLoopIncrement]
Cases that behave correctly (no warning)
- A lambda that captures by reference, defined before the loop and called in the body.
- A global bound decremented through a called function.
- A member bound changed through a member call.
- A struct bound changed through a call that gets a pointer to the struct.
- A bound changed through a pointer alias.
longjmpin the body.
A loop whose body only does continue gets the warning, and that loop really is endless.
Automated review of ee9270e by Claude. The pull request was built and tested locally.
|
Test results for commit ee9270e (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9038/ 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. |
Bail out for volatile or class control variables, and when the variable's address escapes before the loop and the body has a call. Co-authored-by: Cursor <cursoragent@cursor.com>
|
Addressed review comments. Ready for another look. |
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I reproduced two new kinds of false positive. Both come from aliasing.
- The loop variable is changed in the body through a reference that was bound before the loop. The fix for the earlier comment about escaped variables (C11) only bails out when the body also contains a call.
int &r = i; for (i = 0; i < n;) { r++; }therefore gets the warning, although the loop ends. Through a pointer,(*p)++, the PR gives no warning. - The bound is read through a pointer or reference, and a call in the body changes the object behind it. Examples are
i < *pandi < limwherelimis aconst int&.findExpressionChangeddoesn't see that the call changes the object, so the loop gets the warning, although it ends.
The fixes for the earlier review comments (C2, C3, C4, C11) are in place, and their tests pass.
Comments
@willgarvin, please fix, resolve or reply to the open and new comments: #7, #8.
Testing
Build and tests
- I built
cppcheckandtestrunnerin /work/pr. ./testrunner TestOther: 256 tests, 0 failed.pytest other_test.py -k active_unusedfunction: 4 passed.
False positives. Command: ./cppcheck -q --enable=warning --library=std <file>. In each case below the loop does end, but the check reports it.
// a2.cpp – loop variable changed through a reference bound before the loop (no call in the body)
void f(int n) {
int i;
int &r = i;
for (i = 0; i < n;) { r++; }
}a2.cpp:4:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
The same loop with int i = 0; int &r = i; for (i = 0; n > i;) { ++r; }, and with r = n; in the body, gives the same warning. With a pointer alias, int *p = &i; ... (*p)++;, there is no warning.
// b1.c – bound read through a pointer and changed by a call in the body
int limit = 10;
void shrink(void) { limit = 0; }
void f(void) {
int *p = &limit;
for (int i = 0; i < *p;) { shrink(); }
}b1.c:5:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
// b2.cpp – bound is a const reference parameter that aliases a global changed by a call
int limit = 10;
void shrink() { limit = 0; }
void f(const int &lim) {
for (int i = 0; i < lim;) { shrink(); }
}
void g() { f(limit); }b2.cpp:4:5: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]
A third file has the same pattern with an unknown function: void g(void); void f(int *p) { for (int i = 0; i < *p;) { g(); } }. It gives the same warning.
Cases that behave correctly (no warning):
- Pointer alias taken before the loop or inside the body.
scanf("%d", &i)in the body.- An unknown macro call
NEXT(i). - A template with a dependent type.
- A member bound changed by a member call.
s->nwith an opaque call in the body.v.size()withv.pop_back()in the body.- A
gotoout of a nested range-for.
Automated review of bf1435a by Claude. The pull request was built and tested locally.
|
|
||
| // Address/reference may have escaped before the loop; a call in the body | ||
| // might update the variable through that alias. | ||
| if (addressOrRefTakenBefore(loopVarTok->variable(), forTok) && loopBodyHasCall(scope)) |
There was a problem hiding this comment.
AI review
This bail-out only applies when the body also contains a call. If the variable is changed in the body directly through a reference that was bound before the loop, the check still warns:
void f(int n) {
int i;
int &r = i;
for (i = 0; i < n;) { r++; }
}Output: warning: The loop variable 'i' is not updated in this for-loop, so the loop might never terminate. [missingForLoopIncrement]. findExpressionChanged(loopVarTok, ...) doesn't see the write through r. A pointer alias, (*p)++, is recognised.
Possible fixes:
- Bail out whenever
addressOrRefTakenBefore(...)is true, whether or not the body contains a call. - Or also check the aliases for changes in the body.
| return false; | ||
|
|
||
| // Bound must not be modified in the body (e.g. i < n with n-- in the body) | ||
| if (findExpressionChanged(boundTok, bodyStart, bodyEnd, settings)) |
There was a problem hiding this comment.
AI review
findExpressionChanged(boundTok, ...) doesn't see that a call in the body changes the object that the bound refers to through a pointer or reference. These loops end, but they get the warning:
int limit = 10;
void shrink(void) { limit = 0; }
void f(void) { int *p = &limit; for (int i = 0; i < *p;) { shrink(); } }int limit = 10;
void shrink() { limit = 0; }
void f(const int &lim) { for (int i = 0; i < lim;) { shrink(); } }The same happens with void f(int *p) { for (int i = 0; i < *p;) { g(); } }, where g is unknown.
A possible fix: treat a bound that dereferences a pointer, or that is a reference or a non-local variable, as unstable when the body contains a call that isn't const or pure.
|
Test results for commit bf1435a (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-51-20-36-10.eu-north-1.compute.amazonaws.com/pr-9038/ 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. |
New warning
missingForLoopIncrementto identify for loops whose control variable is never updated (ticket #5459 on Trac)Added brief documentation in
man/checkers/missingForLoopIncrement.md