Why is out-of-bounds pointer arithmetic undefined behaviour?

That’s because pointers don’t behave like integers. It’s undefined behavior because the standard says so.

On most platforms however (if not all), you won’t get a crash or run into dubious behavior if you don’t dereference the array. But then, if you don’t dereference it, what’s the point of doing the addition?

That said, note that an expression going one over the end of an array is technically 100% “correct” and guaranteed not to crash per §5.7 ¶5 of the C++11 spec. However, the result of that expression is unspecified (just guaranteed not to be an overflow); while any other expression going more than one past the array bounds is explicitly undefined behavior.

Note: That does not mean it is safe to read and write from an over-by-one offset. You likely will be editing data that does not belong to that array, and will cause state/memory corruption. You just won’t cause an overflow exception.

My guess is that it’s like that because it’s not only dereferencing that’s wrong. Also pointer arithmetics, comparing pointers, etc. So it’s just easier to say don’t do this instead of enumerating the situations where it can be dangerous.

Leave a Comment