3 ms·
I wonder where their delusion that C89 allows reading past the end of an array comes from...
by cygx 14y ago
I wonder where their delusion that C89 allows reading past the end of an array comes from...
- mikeash 14y agoI can only guess that it comes from the fact that it's legal to have a pointer that points on element past the end of the array. That is, this is legal: int array[16]; int *ptr = array + 16; But it's not legal to actually dereference this pointer. The distinction is confusing to a lot of programmers, used to modern architectures where pointers and integers share registers and you can do crazy things with your pointer variables with no consequences. However, some architectures will crash just for having a bad pointer value. That is, this is not legal: int array[16]; int *ptr = array + 17; Even if you never dereference ptr, this code is still illegal, and the compiler is within its rights to generate code that crashes or makes demons fly out of your nose when it encounters this source. The first case is an exception made to make it easier to iterate over an array. So there's a spot in the C standard that says, essentially, "It is OK to have a pointer that points one element past the end of an array." This is probably not too hard to misread as "It is OK to read one element past the end of an array." Although that is definitely wrong.