array subscript is above array bounds

StuartsProjects
Posts: 14
Joined: Sat Nov 28, 2020 11:05 am

array subscript is above array bounds

Postby StuartsProjects » Tue Jan 05, 2021 4:53 pm

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 ?

  1. uint8_t databuff[100];
  2.  
  3. void loop()
  4. {
  5. }
  6.  
  7. void setup()
  8. {
  9.  uint8_t index, ptr;
  10.    
  11.   //fill data buffer with 0 to 99
  12.   for (index = 0; index <= 99; index++);
  13.   {
  14.   ptr = index;  
  15.   databuff[ptr] = ptr;
  16.   }
  17.  
  18. }

ESP_Sprite
Posts: 9730
Joined: Thu Nov 26, 2015 4:08 am

Re: array subscript is above array bounds

Postby ESP_Sprite » Wed Jan 06, 2021 1:33 am

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.

StuartsProjects
Posts: 14
Joined: Sat Nov 28, 2020 11:05 am

Re: array subscript is above array bounds

Postby StuartsProjects » Wed Jan 06, 2021 8:11 am

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 ?

ESP_Sprite
Posts: 9730
Joined: Thu Nov 26, 2015 4:08 am

Re: array subscript is above array bounds

Postby ESP_Sprite » Wed Jan 06, 2021 9:45 am

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.

StuartsProjects
Posts: 14
Joined: Sat Nov 28, 2020 11:05 am

Re: array subscript is above array bounds

Postby StuartsProjects » Wed Jan 06, 2021 11:32 am

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.

Who is online

Users browsing this forum: Baidu [Spider] and 78 guests