Able to add to array beyond size?

I'm noticing that I'm able to add to an array beyond the initialized size...I think I'm missing something. I'm initializing an array of size 1...but it's letting me add 5 elements to it. What's happening?

1
2
3
4
5
6
7
8
int a = 1, b = 2, c = 3, d = 4, e = 5;
int array[1];
array[0] = a;
array[1] = b;
array[2] = c;
array[3] = d;
array[4] = e;
cout << array[0] << " " << array[1] << " " << array[2] << " " << array[3] << " " << array[4];
Arrays are laid out as a row of elements in memory, e.g.

int arr[3];
|   | arr[0] | arr[1] | arr[2] |   |   |

The empty spaces next to the array are used for other things like other variables or maybe a function. When you access things out-of-bounds like arr[3], you mess with memory that may or may not screw other things up.
Here's an example:
One time when I was writing a basic rogue game, I had two arrays declared next to each other like so:
1
2
int arr1[N][P];
char arr2[M][Q];

When I ran the program, I noticed the map image was always out of whack. After a bit of investigation, I discovered that one piece of code that was supposed to work with arr1 accessed elements out of arr1's bounds. This modified arr2, which held the map image.
What happens is undefined: valid index is a precondition of the built-in array indexing operator, and it's the responsibility of the caller to uphold it.

In practice, the compiled program may be writing those numbers to the memory locations past array (which may cause it to crash some of the time, but not always, or modify unrelated variables, or have no visible effect). Or the writes may be optimized out and the compiled program only has the calls to operator<< without any unsafe operations - it's not important what exactly happens, the code is invalid either way.

Even though they are not required to, some compilers issue diagnostics:

clang says
test.cc:9:1: warning: array index 1 is past the end of the array (which contains
      1 element) [-Warray-bounds]
array[1] = b;
^     ~
test.cc:7:1: note: array 'array' declared here


ibm says
"test.cc", line 9.7: 1540-2909 (W) The subscript 1 is out of range.  The only valid subscript is 0.
This is allowed. However, by writing into memory that the OS hasn't allocated for you, you are stepping into undefined behavior.

The consequences of this are non-deterministic, but a common one is unreliable data. That is, you may be writing into a variable that you declared earlier.
Topic archived. No new replies allowed.