Skip to content

Fix #15225 (FN arrayIndexOutOfBounds: sizeof(arr) unknown when the array dimension contains sizeof of a struct, variable or dereference) - #9037

Merged
danmar merged 4 commits into
cppcheck-opensource:mainfrom
JayToltTech:fix-15225-array-dim-early
Nov 25, 2026
Merged

danmar merged 4 commits into
cppcheck-opensource:mainfrom
JayToltTech:fix-15225-array-dim-early

Conversation

@JayToltTech

@JayToltTech JayToltTech commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

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) or 10 + sizeof(*p) is only marked known by SymbolDatabase::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) where T has an array like that as a member

valueFlowNumber() 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 existing sizeof code works unchanged. Chained ones like char b[sizeof(a)] work too. The pass after ValueFlow stays for dimensions that only become known later.

Array parameters are the other half. sizeof of 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, and sizeof(p) / sizeof(p[0]) isn't evaluated as the element count. The condition is in Variable::isDecayedArrayArgument(), which CheckSizeof had inline. References to arrays and std::array by value keep their full size.

Tests are in TestValueFlow::valueFlowSizeof, plus a new TestBufferOverrun::array_index_79 for the a[sizeof(a)] from the ticket. Both fail without the lib/ change. testrunner passes on macOS arm64 and runformat makes no changes. I haven't run the selfcheck locally.

The const_cast on Dimension in valueflow.cpp is the same one setArrayDimensionsUsingValueFlow() already does. Change it as you see fit.

Copilot AI balanced review requested due to automatic review settings November 16, 2026 23:25

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) or sizeof(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)], where t is a struct whose member array has a sizeof dimension.
  • 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 reports b[8].
  • for (i < sizeof(a)) a[i] with char a[4] now reports index 7.
  • void f(int a[2][3]) { int x[sizeof(a)]; } now gives x[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.

Comment thread lib/symboldatabase.cpp Outdated

bool Variable::isDecayedArrayArgument() const
{
return isArray() && isArgument() && !isReference() && !(isStlType() && getTypeName() == "std::array");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(), "[").

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@dmcppcheck

Copy link
Copy Markdown
Contributor

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/
packages: 1000
Differing warnings: 2 (+2 -0)
AI review: 2 regression (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9037/2026-11-17_17-25-27-a985a2cd5e5b-review.txt)
Timing: -0.3% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9037/2026-11-17_17-25-27-a985a2cd5e5b_timing.html)

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

Copy link
Copy Markdown
Contributor

This pull request has merge conflicts that must be resolved.

@JayToltTech
JayToltTech force-pushed the fix-15225-array-dim-early branch from a985a2c to 825d0c8 Compare November 20, 2026 00:14
@JayToltTech

JayToltTech commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Re the two incompleteArrayFill results from the package run (alsaplayer, MilkyTracker). I agree they're false positives, but they aren't from this PR. checkIncompleteArrayFill() warns whenever the size argument's value equals the element count, and doesn't look at how that value was built. The PR just makes more dimensions known, so the existing check now sees these 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 incompleteArrayFill on main. The fix belongs in the check (e.g. skip when the size argument is sizeof(arr) itself), so I'd keep it out of this PR.

@JayToltTech

Copy link
Copy Markdown
Contributor Author

FYI, the 7 failing CI jobs on ff5868be0 aren't from this PR.

  • The macOS CMake jobs (build_cmake, build_cmake_cxxstd 14/17, build_cmake_boost, build_cmake_tinyxml2) and the "Test Signalhandler" step of build (macos-15) all fail in the CMake configure step. In the signalhandler log it's -Werror=dev turning non-target-directive warnings on the add_compile_options calls in cmake/compileroptions.cmake into errors. The same CMake steps fail on main at aa40a90e54.
  • build_cygwin fails in "Set up Cygwin", before anything builds.
  • build (windows-2025, release) fails one test in test/cli, other_test.py::test_clang_tidy_error_exit. cppcheck got Failed to execute 'clang-tidy.exe' (exitcode: 1) instead of the two use-after-move warnings, so it's clang-tidy on the runner. testrunner passed in the same job, 554 of the cli tests passed.

The previous commit 825d0c85d3 passed both the signalhandler and test/cli steps, and ff5868be0 only changes the std::array condition in isDecayedArrayArgument().

…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.
@JayToltTech
JayToltTech force-pushed the fix-15225-array-dim-early branch from ff5868b to 37c4492 Compare November 21, 2026 13:51

@dmcppcheck dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread lib/valueflow.cpp
return;
for (const Dimension& constDimension : var->dimensions()) {
auto& dimension = const_cast<Dimension&>(constDimension);
if (dimension.known || dimension.num != 0 || !dimension.tok)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 dmcppcheck left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI review

I found no new problems. Both earlier review comments are fixed in the current code:

  • An array parameter of std::array, such as std::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 captures char a[10 + sizeof(S)].
  • for (i <= sizeof(a)/sizeof(a[0])) over int 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 in char a[][N].

A warning that base gives and the PR drops, also correct:

  • struct T { int x; char m[N]; } with N an enumerator: base wrongly sized char 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 sizeof dimension.
  • 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::array exception now requires that no [ follows the name.
  • C10: there is a [<,] skip at lib/valueflow.cpp:439, and the repro is covered by array_index_79, which passes.

Automated review of 3565303 by Claude. The pull request was built and tested locally.

@dmcppcheck

Copy link
Copy Markdown
Contributor

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/
packages: 1000
Differing warnings: 0 (+0 -0)
Timing: +0.1% (http://ec2-16-170-140-253.eu-north-1.compute.amazonaws.com/pr-9037/2026-11-21_20-29-02-3565303ef406_timing.html)

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.

@danmar
danmar merged commit 51dc9b1 into cppcheck-opensource:main Nov 25, 2026
74 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants