Some C or C++ programmers are surprised to find out that even storing an invalid pointer is undefined behavior. However, for heap or stack arrays, it's okay to store the address of one past the end of the array, which allows you to store "end" positions for use in loops.
But is it undefined behavior to form a pointer range from a single stack variable, like:
char c = 'X';
char* begin = &c;
char* end = begin + 1;
for (; begin != end; ++begin) { /* do something */ }
Although the above example is pretty useless, this might be useful in the event that some function expects a pointer range, and you have a case where you simply have a single value to pass it.
Is this undefined behavior?
Best Answer
This is allowed, the behavior is defined and both
begin
andend
are safely-derived pointer values.In the C++ standard section 5.7 (
[expr.add]
) paragraph 4:When using C a similar clause can be found in the the C99/N1256 standard section 6.5.6 paragraph 7.
As an aside, in section 3.7.4.3 (
[basic.stc.dynamic.safety]
) "Safely-derived pointers" there is a footnote:This suggests that pointer arithmetic throughout the stack is implementation-defined behavior, not undefined behavior.