Dangers of under-dimensioning an array

All,

I thought this would come instructional. In brief, if you start accessing out-of-bounds array elements, the code may give you many hours of entertainment :). Look at this code:

byte x[1];
boolean xBool;

void setup()
{
   Serial.begin(115200);
   xBool = true;
}

void loop()
{
   Serial.print (xBool);
   Serial.print (" ");

   x[0] = 66;
   x[1] = 10;

   Serial.write(x, 2);

   delay(500);
}

Have it run (I am using ATMega2560. R3 board with Arduino 1.8.5). Note that the first output of the Boolean variable xBool is 1, but not further on.

Wanna have more fun?

  1. Comment out line 9 (xBool = true;), and change line 2 to: boolean xBool = true; Run. On my Mega2560 board, there is just single "1" printout and that's all...

  2. Comment out line 22 (Serial.write(x, 2);). Output is now fine, so you may never know that a code update may produce bool cookies.

Bottomline: the problem is, of course on line 1, where the array was under-allocated, so assignment on line 20 writes to a location that may be used by something else. This is an excerpt of a much larger code that behaved strangely, and where indexes on lines 19 and 20 were variables, so not as obviously out-of-bounds, until runtime.

In the old times, (Fortran and Cobol era), code would safely crash with appropriate "Array out of bounds" message on the terminal screen...

If you comment out the writing of x the variable is never accessed and therefore optimized out of the program entirely,

so assignment on line 20 writes to a location that may be used by something else

it will write to the variable location of xbool which is declared just after and used. more fun is creating a for loop and and writing to the memory location of the counter or part of the variable used in the condition for unexpected results.

where indexes on lines 19 and 20 were variables, so not as obviously out-of-bounds, until runtime.

In the old times, (Fortran and Cobol era), code would safely crash with appropriate "Array out of bounds" message on the terminal screen...

but an arduino doesn't really have a terminal screen and an Array is really not much more than a pointer to data.

Zigmund:
In the old times, (Fortran and Cobol era), code would safely crash with appropriate "Array out of bounds" message on the terminal screen...

No, in the real Old Times, you would turn up to collect your overnight batch job, to find a core dump (all 128k bytes!) printed on half a box of 132 column fan-fold, along with stern note from the senior operator telling you to check your code more thoroughly before submission.
If you were lucky, your returned card deck would be unshuffled.