Are non dereferenced iterators past the “one past-the-end” iterator of an array undefined behavior?

Yes, your program has undefined behaviour if you form such a pointer.

That’s because the only way you can do so is to increment a valid pointer past the bounds of the object it points inside, and that is an undefined operation.

[C++14: 5.7/5]: When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th and i − n-th elements of the array object, provided they exist. Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined.

An uninitialised pointer is not the same thing because you never did anything to “get” that pointer, other than declaring it (which is obviously valid). But you can’t even evaluate it (not dereference — evaluate) without imbuing your program with undefined behaviour. Not until you’ve assigned it a valid value.

As a sidenote, I would not call these “past-the-end” iterators/pointers, a term in C++ which specifically means the “one past-the-end” iterator/pointer, which is valid (e.g. cend(foo) itself). You’re waaaay past the end. 😉

Leave a Comment