A colleague of mine recently got bitten badly by writing out of bounds to a static array on the stack (he added an element to it without increasing the array size). Shouldn’t the compiler catch this kind of error? The following code compiles cleanly with gcc, even with the -Wall -Wextra options, and yet it is clearly erroneous:
int main(void) { int a[10]; a[13] = 3; // oops, overwrote the return address return 0; }
I’m positive that this is undefined behavior, although I can’t find an excerpt from the C99 standard saying so at the moment. But in the simplest case, where the size of an array is known as compile time and the indices are known at compile time, shouldn’t the compiler emit a warning at the very least?
GCC does warn about this. But you need to do two things:
ais, and that you ran off the edge..
BTW: If you returned a[13] in your test program, that wouldn’t work either, as GCC optimizes out the array again.