I like to write example programs that are devoid of warnings, I have all complier warnings turned on in the IDE to make sure none slip by.
I was writing some code to test large scale file transfers over LoRa so I wanted to fill the data buffer being sent with numbers so I could easily check on the receiver that everything was working OK. I wrote some code for a Pro Mini and it works just fine no, errors. I then tried the code on a DUE and got a warning 'array subscript is above array bounds'
The part of the code that causes the warning is below;
uint8_t databuff[128];
void loop()
{
}
void setup()
{
uint8_t index, ptr;
//fill data buffer with numbers 0 to 127
for (index = 0; index <= 127; index++);
{
ptr = index;
databuff[ptr] = ptr;
}
}
Now of course the code, if written badly, could address beyond the array, but it does not.
So why the warning ?
When compiled on an ESP32, the above code reports an error and wont compile, so I have asked over in the ESP32 forums why this is so.
Sketch uses 206435 bytes (15%) of program storage space. Maximum is 1310720 bytes.
Global variables use 14684 bytes (4%) of dynamic memory, leaving 312996 bytes for local variables. Maximum is 327680 bytes.
Windows 10
IDE 1.8.13
WEMOS D1 MINI ESP32 or a clone ESP32 Dev module
C:\Users\Stuart\Desktop\Code\Code.ino: In function 'void setup()':
Code:12: error: array subscript is above array bounds [-Werror=array-bounds]
databuff[ptr] = ptr;
^
cc1plus.exe: some warnings being treated as errors
exit status 1
array subscript is above array bounds [-Werror=array-bounds]
Not here. I just ran up a new 'portable' install of IDE 1.8.13, installed the 1.0.4 ESP32 plug in and I get the same array subscript is above array bouns error.
void loop()
{
}
void setup()
{
uint8_t index, ptr;
//fill data buffer with numbers 0 to 127
for (index = 0; index <= 127; index++);
{
ptr = index;
databuff[ptr] = ptr;
}
}
You have a semicolon after your for loop header, so the ptr = index code runs after the for loop has ended, and at this point, the value of index is 128 (i.e. the first value for which the for loop condition is false), hence it is out of bounds in the array.
You should always make your variables as local as possible, that would have avoided this issue:
for (uint8_t index = 0; index <= 127; index++)
{
uint8_t ptr = index; // weird name for an index variable ...
databuff[ptr] = ptr;
}
It compiled for me, but I have just discovered that I had compiler warnings set to None in the IDE preferences. Setting it to All, which it should have been in the first place, causes the error to be reported
I wonder what other settings I have got wrong on this new PC ?