Out of bounds checking is something that you are probably used to from some higher level language like Java. However in C/C++ it is not done by default. It gives you a small performance hit to check the bounds of the array and therefore the C rationale is to have you do it manually in case you need it to offer the best possible performance. C++ STL containers like vector
usually support an at()
operation to perform bound-checking and since you can overload the []-operator you can also enable bound-checks for array-style access.
If array
is a raw pointer a statement like array[i]
comes down to this in C/C++:
*(array + i)
which is a simple addition of address + offset. The following statements are thus equivalent:
*(array + i), *(i + array), array[i], i[array]
What happens internally is that you take the address stored in the pointer, add i-times the size of the array type to it and then de-reference this address.
So what happens if you specify an index that is bigger than the array, is that you access memory that does not belong to the array. Effectively you read random data that is next to the array in memory. This is a typical source of buffer-overflows if the address is written to. If the memory you are trying to access does not belong to your process, you will get a segfault.