Ambiguity in the standard on undefined behaviour of out of range pointer

China☆狼群 提交于 2019-12-04 16:10:15

The paragraph you're quoting refers to pointer arithmetic, not to evaluation of pointers.

It states that the only time pointer addition p + i is defined is if
(treating subtraction of i as equivalent to addition of -i)

  1. p points to an element of an array object or one past the last element, and
  2. p + i points to an element of the same array object, or one past the last element

If p isn't a pointer to an array element or "one past the end" - for instance if it is the null pointer or "two past the end" - the behaviour is undefined.
You don't need to dereference the result to cause undefined behaviour - the effect of the addition itself is undefined.

That is to say

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

and likewise

int *p = nullptr;
p++; // Undefined
p--; // Still undefined

"The evaluation" means the evaluation of the additive operation; thus UB would not occur for (say) static_cast<int*>(nullptr) + 1 within a non-evaluated context (sizeof, decltype, etc).

It does not mean "the evaluation of the pointer", and certainly not dereferencing it; if the standard had intended that interpretation, it would have said so.

Incrementing then decrementing a null pointer is still undefined behaviour. When UB occurs, anything can happen, so this would be a valid sequence of an events:

  1. Increment null pointer. Undefined behaviour, so we'll set the pointer to 0xDEADBEEF because we can.
  2. Decrement pointer. Also undefined behaviour unless 0xDEADBEEF happens to be in a valid array after the first element.
  3. Dereference pointer. Issue forth nasal demons.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!