超出 C++ 的界限和未定义的行为 [英] Out of the bounds in C++ and undefined behaviour
问题描述
我知道在 C++ 中访问缓冲区边界是未定义的行为.
这是来自 cppreference 的示例:
I know that in c++ access out of buffer bounds is undefined behaviour.
Here is example from cppreference:
int table[4] = {};
bool exists_in_table(int v)
{
// return true in one of the first 4 iterations or UB due to out-of-bounds access
for (int i = 0; i <= 4; i++) {
if (table[i] == v) return true;
}
return false;
}
但是,我在 C++ 标准中找不到相应的段落.
任何人都可以指出我在标准中解释这种情况的具体段落吗?
But, I can't find according paragraph in c++ standard.
Can anyone point me out on concrete paragraph in standard where such case is explained?
推荐答案
这是未定义的行为.我们可以并列几段经文来证实这一点.首先,我不会明确证明,table[4]
是 *(table + 4)
.我们只需要问自己指针值table + 4
的属性以及它与间接运算符的要求有何关系.
It's undefined behavior. We can juxtapose a couple of passages to be convinced of it. First, and I won't explicitly prove it, table[4]
is *(table + 4)
. We need only ask ourselves the properties of the pointer value table + 4
and how it relates to the requirements of the indirection operator.
在指针上,我们有这样一段话:
On the pointer, we have this passage:
[basic.compound]
3 指针类型的每个值是以下之一:
3 Every value of pointer type is one of the following:
- 指向对象或函数的指针(据说该指针指向对象或函数),或
- 超过对象末尾的指针([expr.add]),或
- 该类型的空指针值,或
- 无效的指针值.
我们的指针是第二个项目符号的类型,而不是第一个.至于间接运算符:
Our pointer is of the second bullet's type, not the first. As for the indirection operator:
[expr.unary.op]
1 一元 * 运算符执行间接寻址:应用它的表达式应该是指向对象类型的指针,或指向函数类型的指针,结果是引用表达式指向的对象或函数的左值.如果表达式的类型为pointer to T
",则结果的类型为T
".
1 The unary * operator performs indirection: the expression to which it is applied shall be a pointer to an object type, or a pointer to a function type and the result is an lvalue referring to the object or function to which the expression points. If the type of the expression is "pointer to T
", the type of the result is "T
".
我希望通过阅读本段可以明显看出,该操作是为上一段中第一个项目符号描述的类别的指针定义的.
I hope it's obvious from reading this paragraph that the operation is defined for a pointer of the category described by the first bullet in the preceding paragraph.
因此,我们将操作应用于未定义其行为的指针值.结果是未定义的行为.
So we apply an operation to a pointer value for which its behavior is not defined. The result is undefined behavior.
这篇关于超出 C++ 的界限和未定义的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!