超出范围指针的未定义行为的标准中的模糊性 [英] Ambiguity in the standard on undefined behaviour of out of range pointer

查看:173
本文介绍了超出范围指针的未定义行为的标准中的模糊性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ISO IEC 14882-2011§5.7/ 5 国家:


如果指针操作数和结果指向同一数组对象的元素,或者一个超过数组对象的最后一个元素,评估不会产生溢出;

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.

此部分在此不时地用于stackoverflow。例如,争论为什么 nullptr 的指针的增量是UB,如在这里。然后将其解释为,具有不指向数组对象的元素的指针。是未定义的行为。

This section is used here on stackoverflow from time to time. For instance to argue why the increment of a pointer to nullptr is UB like here. It is then interpreted as, having a pointer that does not point to an element of an array object. Is undefined behaviour.

然而,当我读这个时,我理解它指的是指针的评估是UB。这意味着有这样的指针是明确定义的行为。并且当尝试解除引用它时,行为变得不确定。

However, when I read this I understood it to refer to the evaluation of the pointer being UB. Which would mean that having such a pointer is well defined behaviour. And the behaviour becomes undefined when one tries to dereference it.

这意味着例如,将有效指针递增到数组边界之外是合法的。之后再次减少是合法的。并且由于指针将是与增量之前相同的值,所以评估也是合法的。

Which would mean that for example, incrementing a valid pointer beyond the array boundary is legal. Decrementing it again afterwards is legal. And since the pointer will then be the same value as before the increment, the evaluation is legal too.

这两个是哪一个?

推荐答案

你引用指的是指针运算,而不是指针的求值。

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

它规定定义唯一的时间指针添加 p + i 是如果

(处理减去 i 等同于添加 -i

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 指向数组对象的元素或一个超过最后一个元素的元素,

  2. p + 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

如果 p 不是指向数组元素或one past the end的指针,是空指针或两个过去的结束 - 行为是未定义的。

您不需要取消引用结果导致未定义的行为 - 添加本身的影响是未定义的。

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.

也就是说

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

,同样

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

这篇关于超出范围指针的未定义行为的标准中的模糊性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆