Ambiguity in the standard for the behavior of an undefined pointer out of range

ISO IEC 14882-2011 §5.7 / 5 States:

If both pointer operands and the result point to elements of the same array object or one after the last element of the array object, the evaluation should not lead to overflow; otherwise, the behavior is undefined.

This section is used here in stackoverflow from time to time. For example, to state why the nullptr pointer increment is UB, for example here . Then it is interpreted as having a pointer that does not point to an element of an array object. This behavior is undefined.

However, when I read this, I realized that this refers to evaluating a pointer being UB. This would mean that having such a pointer is a well-defined behavior. And the behavior becomes undefined when you try to dereference it.

This means that, for example, incrementing a valid pointer outside the array boundary is legal. After that, its further reduction is legal. And since the pointer will be the same value as before the increment, the estimate is also legal.

Which of the two cases?

+2
c ++ undefined-behavior language-lawyer semantics c ++ 11
May 21 '15 at 9:11
source share
3 answers

The paragraph you are quoting refers to pointer arithmetic, and not to pointer evaluation.

It states that the only addition of the p + i pointer is if if (considering subtracting i equivalent to adding -i )

  • p points to an element of an array object or one after the last element, and
  • p + i points to an element of the same array object or one after the last element

If p not a pointer to an array element or "one after the end" - for example, if it is a null pointer or "two ends" - the behavior is undefined.
You don’t have to play the result to trigger undefined behavior - the effect of adding undefined itself.

I.e

 int p[1] = {0}; int *q = p; // OK q = q + 1; // OK - one past the end int *r = q + 1; // Undefined behaviour r = r - 1; // Doesn't make r valid or the program un-undefined 

as well as

 int *p = nullptr; p++; // Undefined p--; // Still undefined 
+4
May 21 '15 at 10:00
source share

“Evaluation” means the evaluation of an additive operation; thus, UB will not have a place for (say) static_cast<int*>(nullptr) + 1 in an undefined context ( sizeof , decltype , etc.).

This does not mean "pointer rating" and, of course, does not play it; if the standard suggested this interpretation, he would say so.

+3
May 21 '15 at 9:21
source share

An increment decrementing a null pointer is still undefined. When UB happens, everything can happen, so this will be a valid sequence of events:

  • Increases the null pointer. undefined, so we will set the pointer to 0xDEADBEEF because we can.
  • Decrease pointer Also, the behavior is undefined if 0xDEADBEEF is in a valid array after the first element.
  • Dereference pointer Release the nasal demons.
0
May 21 '15 at 9:23
source share



All Articles