Page 1 of 1
array subscript is above array bounds
Posted: Tue Jan 05, 2021 4:53 pm
by StuartsProjects
Why does the code below generate an 'array subscript is above array bounds' compiler error ?
I can see that when the for loop closes then it has assigned index to 100 and that is out of bounds of the array, even though its never used.
Perhaps a warning that you migh be doing something bad, but why a compiler error ?
uint8_t databuff[100];
void loop()
{
}
void setup()
{
uint8_t index, ptr;
//fill data buffer with 0 to 99
for (index = 0; index <= 99; index++);
{
ptr = index;
databuff[ptr] = ptr;
}
}
Re: array subscript is above array bounds
Posted: Wed Jan 06, 2021 1:33 am
by ESP_Sprite
Because even addressing an array out of bounds is defined to give 'undefined behaviour' in the C specs. You might assume that nothing bad happens, but that is far from guaranteed.
Here's a real-world example.
Re: array subscript is above array bounds
Posted: Wed Jan 06, 2021 8:11 am
by StuartsProjects
I am fully aware that addressing an array out of bounds can cause bad things to happen.
And the code posted does not do that.
Within the Arduino IDE, the Atmel processors generate no warning for the code, which is the correct response, since the code does not address the array out of bounds.
Again in the Arduino IDE, some of the processors, DUE for instance, generate a warning only which is sort of acceptable, since the code actually compilies.
So why does the ESP32 plugin for Arduino report it as an error when it is not ?
Re: array subscript is above array bounds
Posted: Wed Jan 06, 2021 9:45 am
by ESP_Sprite
Ah, never mind, just looked at your code again. I think that if the code did what you intended it to do (fill databuf[0..99] with zeroes) the compiler would not complain indeed. However, there is a subtle bug in it and the compiler is 100% right that you would write past the end of the array. Hint, take a very, very good look at line 12/13 of your code, they likely do not do what you think they do.
As to why Arduino does not generate the warning: I dunno, possibly the compiler warnings are set less strict than that, or perhaps the code did not have the bug when you compiled it in that environment.
Re: array subscript is above array bounds
Posted: Wed Jan 06, 2021 11:32 am
by StuartsProjects
Ah, the ;
So there is a problem, but its turned around, now the question is why does the Atmel part of the IDE not spot the problem ............
TVM.