Repository navigation
Fix #15225 (FN arrayIndexOutOfBounds: sizeof(arr) unknown when the array dimension contains sizeof of a struct, variable or dereference) - #9037
Conversation
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The fix works for the cases in the ticket, and the full testrunner passes. I found one new problem, a small one: the new Variable::isDecayedArrayArgument() skips every std::array variable, including a parameter declared as an array of std::array. For void f(std::array<int, 4> a[2]), sizeof(a) still gets 16 instead of the pointer size, and sizeofwithsilentarraypointer gives no warning. This was already wrong on base, but the PR now says this helper is the rule for array parameters.
Some results change as expected from the pointer-size change. For example, void f(char a[4]) { memset(a, 0, sizeof(a)); } now also reports bufferAccessOutOfBounds. The old a[100] warning for void f4(char a[100]) { a[sizeof(a)] = 0; } is gone. Both are correct, since sizeof(a) is the pointer size, and sizeofwithsilentarraypointer still warns on those lines. Apart from the item above, I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | The std::array exclusion also covers arrays of std::array, e.g. std::array<int,4> a[2] |
AI review | lib/symboldatabase.cpp:2723 |
🆕 New (false negative) |
@JayToltTech, please fix, resolve or reply to the open and new comments: #1.
For #1 (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
Build: I built cppcheck and testrunner in pr/ and cppcheck in base/. Both built without errors.
Tests: ./testrunner TestValueFlow TestBufferOverrun TestSizeof TestSymbolDatabase passed. The full ./testrunner -q also passed: 5420 tests, 0 failed.
My own tests: I wrote test files in scratch/ and ran base and PR on them with --enable=all.
What gets a value now that did not on base:
- Local arrays whose dimension contains
sizeof(struct S)orsizeof(var), including multi-dimensional ones. memset(a, 0, sizeof(a)+1).for (i <= sizeof(a)/sizeof(a[0])).- Chained declarations such as
char b[sizeof(t)], wheretis a struct whose member array has asizeofdimension. - Template functions like
char a[2 + sizeof(T)]. - Member arrays.
All of these now give the expected arrayIndexOutOfBounds or bufferAccessOutOfBounds. References to arrays, std::array by value and VLAs behave the same as on base.
What changed for array parameters:
void f(char a[4]) { char b[sizeof(a)]; b[8]=0; }now reportsb[8].for (i < sizeof(a)) a[i]withchar a[4]now reports index 7.void f(int a[2][3]) { int x[sizeof(a)]; }now givesx[8].
All of these are correct for 64-bit pointers.
The problem I found (also wrong on base, but the new helper keeps it):
#include <array>
void f1(std::array<int, 4> a[2]) { int x[sizeof(a)]; x[8] = 0; x[32] = 0; }
void g(std::array<int, 4> a[2]) { int x = sizeof(a); }pr/cppcheck --debug --verbose t4.cpp shows sizeof always 16 for g. It should be 8, the pointer size. Running pr/cppcheck -q t3.cpp reports only Array 'x[16]' accessed at index 32. It misses x[8], and there is no sizeofwithsilentarraypointer warning.
Side note: when the parameter is decayed, sizeof(p)/sizeof(p[0]) now gets no value at all, where base gave a wrong one. The reason is that the division branch in vf_common.cpp does not fall back to the %var% ) branch. This is conservative and matches how base already handles other divisions that do not match, so I am not reporting it.
Automated review of a985a2c by Claude. The pull request was built and tested locally.
|
|
||
| bool Variable::isDecayedArrayArgument() const | ||
| { | ||
| return isArray() && isArgument() && !isReference() && !(isStlType() && getTypeName() == "std::array"); |
There was a problem hiding this comment.
AI review
The std::array exclusion is meant for a std::array passed by value. It also matches a parameter declared as an array of std::array, and that parameter does decay to a pointer:
void g(std::array<int, 4> a[2]) { int x = sizeof(a); }--debug shows sizeof always 16, but the value should be the pointer size (8). In void f1(std::array<int, 4> a[2]) { int x[sizeof(a)]; x[8] = 0; } the x[8] access is missed, and sizeofwithsilentarraypointer does not warn.
The condition came over from CheckSizeof unchanged, but this helper is now what ValueFlow uses to decide what an array parameter is. One possible fix is to apply the std::array exception only when the parameter has no [...] of its own, for example when !Token::simpleMatch(nameToken()->next(), "[").
There was a problem hiding this comment.
Fixed in ff5868b. The std::array exception now only applies when the parameter has no [...] of its own, so std::array<int, 4> a[2] is treated as a pointer and std::array by value keeps its full size.
Added the a[2] case to TestValueFlow::valueFlowSizeof (pointer size) and to the #14860 test in TestSizeof::sizeofForArrayParameter (sizeofwithsilentarraypointer). Both fail without the change. Your f1 repro now reports x[8] too.
|
Test results for commit a985a2c (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9037/ 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. |
|
This pull request has merge conflicts that must be resolved. |
a985a2c to
825d0c8
Compare
|
Re the two Same thing on literal dimensions, which main already knows: void f1() { bool b[10]; memset(b, 0, sizeof(b)); }
void f2() { short p[10]; short q[10]; memcpy(p, q, sizeof(p) / 2); }Both warn |
|
FYI, the 7 failing CI jobs on
The previous commit |
…ray dimension contains sizeof of a struct, variable or dereference) A dimension such as 10 + sizeof(struct S) was only marked known by SymbolDatabase::setArrayDimensionsUsingValueFlow(), which runs after all ValueFlow passes. Every reader inside ValueFlow saw it as unknown, so sizeof(arr), sizeof(arr) / sizeof(arr[0]) and sizeof of a struct that contains such an array got no value. valueFlowNumber() now sets the dimension when the token walk reaches the end of the array declaration, where constant folding has already given the dimension token a known value. Declarations precede uses, so the existing sizeof code then works unchanged, including for chained declarations such as char b[sizeof(a)]. The pass after ValueFlow stays for dimensions that only become known later. With more dimensions known, sizeof of an array function parameter would get the size of the array more often. It is a pointer, so sizeof now gives the pointer size and sizeof(p) / sizeof(p[0]) is no longer evaluated as the element count. The condition moves to Variable::isDecayedArrayArgument(), shared with CheckSizeof.
ff5868b to
37c4492
Compare
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The new valueFlowArrayDimensions() in lib/valueflow.cpp gives a wrong size for a dimension that comes from a std::array template argument. For std::array<char, 3 + sizeof(S)> a[2], the template-argument dimension gets the value of its first token, 3. That value is stored with num != 0, so setArrayDimensionsUsingValueFlow() later skips the dimension and never corrects it. As a result sizeof(a) becomes 3, and char buf[sizeof(a)]; buf[5] = 0; gives a new false positive, arrayIndexOutOfBounds. The earlier comment about arrays of std::array parameters is fixed. Apart from this I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | std::array exclusion also covers parameters declared as arrays of std::array | AI review | lib/symboldatabase.cpp:2723 |
✅ Fixed |
| 2 | Package run shows 2 new incompleteArrayFill warnings (AI review: regressions) | @dmcppcheck | general | 💬 Answered: Author: false positives of the existing check, which also happen on main with literal dimensions; fix belongs in the check |
| 3 | Template-argument dimensions (std::array<T, 3 + sizeof(S)> a[2]) get the value of their first token | AI review | lib/valueflow.cpp:437 |
🆕 New |
@JayToltTech, please fix, resolve or reply to the open and new comments: #3.
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Tests: ./testrunner TestValueFlow TestBufferOverrun TestSizeof TestSymbolDatabase passed with 0 failures.
Earlier comment C3: void h(std::array<int, 4> a[2]) { int x = sizeof(a); } now gives sizeofwithsilentarraypointer, so the problem is fixed.
Other checks: in a scratch file I compared base and PR on several cases:
- Local arrays, member arrays, multi-dimensional arrays and arrays captured by a lambda, all with a
sizeof(S)dimension. sizeof(a)/sizeof(*a).- Array parameters, including
char *a[10], where base gave 80 and the PR gives 8, which is correct. - References to arrays.
They all behaved as intended. A reference parameter char (&a)[10 + sizeof(S)] still gets no value for sizeof(a), the same as on base.
New false positive:
#include <array>
struct S { char c[4]; };
void f() {
std::array<char, 3 + sizeof(S)> a[2];
char buf[sizeof(a)];
buf[5] = 0;
}base/cppcheck -q c.cpp reports nothing. pr/cppcheck -q c.cpp reports:
c.cpp:6:8: error: Array 'buf[3]' accessed at index 5, which is out of bounds. [arrayIndexOutOfBounds]
With --debug, int x = sizeof(a); shows sizeof always 3 on the PR and no value on base. The correct size of a is 14.
Automated review of 37c4492 by Claude. The pull request was built and tested locally.
| return; | ||
| for (const Dimension& constDimension : var->dimensions()) { | ||
| auto& dimension = const_cast<Dimension&>(constDimension); | ||
| if (dimension.known || dimension.num != 0 || !dimension.tok) |
There was a problem hiding this comment.
AI review
This loop also goes over dimensions that come from a template argument, where Token::Match(dimension.tok->previous(), "[<,]") is true. setArrayDimensionsUsingValueFlow() handles those separately, because dimension.tok there is only the first token of the argument and there may be no AST. Here dimension.tok->getKnownValue() returns the value of that first token. Because num is then non-zero, the later pass skips the dimension and never corrects it.
#include <array>
struct S { char c[4]; };
void f() {
std::array<char, 3 + sizeof(S)> a[2];
char buf[sizeof(a)];
buf[5] = 0;
}On the PR, sizeof(a) gets the value 3, and cppcheck reports Array 'buf[3]' accessed at index 5, which is out of bounds. [arrayIndexOutOfBounds]. Base gives no warning.
One possible fix is to skip dimensions where Token::Match(dimension.tok->previous(), "[<,]") and leave them to setArrayDimensionsUsingValueFlow().
There was a problem hiding this comment.
Fixed in 3565303. valueFlowArrayDimensions() now skips dimensions that come from a template argument ([<,] before dimension.tok) and leaves them to setArrayDimensionsUsingValueFlow(), as you suggested.
Your repro no longer warns, and sizeof(a) is 14. I added it to TestBufferOverrun::array_index_79, where it fails without the change.
…lueFlow For std::array<char, 3 + sizeof(S)> a[2], dimension.tok is only the first token of the template argument and may have no AST, so its known value was that of 3 alone. With num set, the later pass skipped the dimension and sizeof(a) became 3, giving a false arrayIndexOutOfBounds.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
I found no new problems. Both earlier review comments are fixed in the current code:
- An array parameter of
std::array, such asstd::array<int, 4> a[2], is now treated as decayed to a pointer. - Dimensions that come from a template argument are skipped in
valueFlowArrayDimensions().
My extra cases gave either the same result as base or a correct new result. That covers member and chained dimensions, lambdas, out-of-line member functions, pointer-to-array parameters and VLAs. The full testrunner passes.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | std::array exclusion also covers parameters declared as arrays of std::array | AI review | lib/symboldatabase.cpp:2723 |
✅ Fixed |
| 2 | Package run shows 2 new incompleteArrayFill warnings (AI review: regressions) | @dmcppcheck | general | 💬 Answered: Author: these are false positives of the existing check, which main also gives with literal dimensions; the fix belongs in the check |
| 3 | Template-argument dimensions get the value of their first token, giving an FP for std::array<char, 3 + sizeof(S)> a[2] | AI review | lib/valueflow.cpp:437 |
✅ Fixed |
Testing
Build: make -j8 cppcheck testrunner in pr/ and make -j8 cppcheck in base/ both built without errors.
Tests:
./testrunner TestValueFlow TestBufferOverrun TestSizeof TestSymbolDatabase: 737 tests, 0 failed.- Full
./testrunner -q: 5423 tests, 0 failed.
My own tests: I wrote three files in scratch/ (t1.c, t2.cpp, t3.cpp) and ran base/cppcheck -q and pr/cppcheck -q on them.
New warnings on the PR, all correct:
b[14]in a lambda that captureschar a[10 + sizeof(S)].for (i <= sizeof(a)/sizeof(a[0]))overint a[10 + sizeof(S)].sizeof(a)gives the pointer size for array parameters in lambdas, in out-of-line member functions (void K::m(char a[100])) and inchar a[][N].
A warning that base gives and the PR drops, also correct:
struct T { int x; char m[N]; }withNan enumerator: base wrongly sizedchar a[sizeof(struct T)]as 4 and warned, the PR does not.
Same result on base and PR:
- Reference-to-array parameters.
- Pointer-to-array parameters
int (*a)[10]. - VLAs with a
sizeofdimension. - A static-const member dimension.
- An inline member function that uses a member array declared later in the class (still a false negative).
Problems that already exist on base and that the PR does not change, so I am not reporting them:
sizeof(*p)for a pointer to an array gives 8.std::array<char,4> a[2+sizeof(S)]gets size 4.
Earlier comments: I checked both against the code:
- C3: the
std::arrayexception now requires that no[follows the name. - C10: there is a
[<,]skip atlib/valueflow.cpp:439, and the repro is covered byarray_index_79, which passes.
Automated review of 3565303 by Claude. The pull request was built and tested locally.
|
Test results for commit 3565303 (tools/test-my-pr.py, main compared to this PR): Test: http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9037/ 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. |
https://trac.cppcheck.net/ticket/15225
Replaces #9036, which I've closed. That one patched a single reader of the array dimension, and the review there found it gave a false positive for array parameters. Looking at why turned up the same cause in two more places, so this fixes the cause.
A dimension like
10 + sizeof(struct S),10 + sizeof(var)or10 + sizeof(*p)is only marked known bySymbolDatabase::setArrayDimensionsUsingValueFlow(), and that runs after all the ValueFlow passes. So everything inside ValueFlow sees the dimension as unknown, and none of these get a value:sizeof(arr)sizeof(arr) / sizeof(arr[0])sizeof(struct T)whereThas an array like that as a membervalueFlowNumber()now sets the dimension when the token walk gets to the end of the array declaration. Constant folding has already given the dimension token a known value by then, and declarations come before uses, so the existingsizeofcode works unchanged. Chained ones likechar b[sizeof(a)]work too. The pass after ValueFlow stays for dimensions that only become known later.Array parameters are the other half.
sizeofof an array function parameter is the size of a pointer, but it was being evaluated as the size of the array.void f(char p[10])gave 10 on main already, and knowing more dimensions would have spread that. It gives the pointer size now, andsizeof(p) / sizeof(p[0])isn't evaluated as the element count. The condition is inVariable::isDecayedArrayArgument(), whichCheckSizeofhad inline. References to arrays andstd::arrayby value keep their full size.Tests are in
TestValueFlow::valueFlowSizeof, plus a newTestBufferOverrun::array_index_79for thea[sizeof(a)]from the ticket. Both fail without thelib/change. testrunner passes on macOS arm64 andrunformatmakes no changes. I haven't run the selfcheck locally.The
const_castonDimensioninvalueflow.cppis the same onesetArrayDimensionsUsingValueFlow()already does. Change it as you see fit.