Why do I receive an array out of bounds error when building code generated with MATLAB Coder in R2024b?
2 views (last 30 days)
Show older comments
MathWorks Support Team
on 9 Jul 2025
Answered: MathWorks Support Team
on 9 Jul 2025
I am using MATLAB Coder R2024b for ARM-cortex A using ARM GNU GCC v12.3 toolchain. When I attempt to build the generated code, I receive the following error message related to the file "coder_array.h":
In member function 'void coder::detail::data_ptr<T, SZ>::construct_last_n(T*, SZ) [with T = double; SZ = int]',
inlined from 'void coder::detail::data_ptr<T, SZ>::reserve(SZ) [with T = double; SZ = int]' at path/to/coder_array.h:157:29,
inlined from 'void coder::detail::data_ptr<T, SZ>::reserve(SZ) [with T = double; SZ = int]' at path/to/coder_array.h:154:10,
inlined from 'void coder::detail::data_ptr<T, SZ>::resize(SZ) [with T = double; SZ = int]' at path/to/coder_array.h:172:20,
inlined from 'void coder::array_base<T, SZ, N>::ensureCapacity(SZ) [with T = double; SZ = int; int N = 2]' at path/to/coder_array.h:783:21:
path/to/coder_array.h:196:17: error: array subscript 0 is outside array bounds of 'double [0]' [-Werror=array-bounds]
196 | new (&_data[i]) T();
| ^~~~~~~~~~~~~~~~~~~
Why is this error occurring?
Accepted Answer
MathWorks Support Team
on 9 Jul 2025
This is a bug in GCC and a false error. This issue is only reproducible with the "-O3" or "-Warray-bounds" flags enabled. A fragment of the generated code from "coder_array.h" can be seen as:
for (i = size_ - _n; i < size_; i++) {
new (&_data[i]) T();
}
This array allocates "_n" elements, but this allocation never occurs for 0 elements. GCC analyzer is conservatively analyzing the code. The analyzer of the compiler is not strong enough to understand that this 0 memory allocation can never occur.
In terms of a workaround, you can add the following to the beginning of the "reserve()" function in "coder_array.h":
if (_n <= 0) {
return;
}
An alternative workaround would be to change the compilation flags in your environment. If you remove the "-O3" or switch the "-Warray-bounds" flag to "–Wno-array-bounds" your code should compile successfully.
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!