在 C 和 C++ 中访问超出限制的数组 [英] Access array beyond the limit in C and C++

查看:49
本文介绍了在 C 和 C++ 中访问超出限制的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int data[8];
data[9] = 1;

C++ 标准对此有何评论?这是未定义的行为吗?

What does the C++ standard say about it? Is this undefined behaviour?

至少 C 编译器 (gcc -std=c99 -pedantic -W -Wall) 对此没有任何说明.

At least the C compiler (gcc -std=c99 -pedantic -W -Wall) doesn't say anything about it.

推荐答案

访问数组边界外是未定义行为,来自 c99 草案标准 部分 Annex J.2 J.2 未定义行为 包括以下几点:

Accessing outside the array bounds is undefined behavior, from the c99 draft standard section Annex J.2 J.2 Undefined behavior includes the follow point:

数组下标超出范围,即使对象显然可以通过给定下标(如左值表达式 a[1][7] 给定声明 inta[4][5]) (6.5.6).

An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a[1][7] given the declaration int a[4][5]) (6.5.6).

C++ 标准草案5.7 Additive operators 段落 5 中说:

and the draft C++ standard in section 5.7 Additive operators paragraph 5 says:

当一个具有整数类型的表达式与指针相加或相减时,结果具有指针操作数的类型.如果指针操作数指向一个数组对象的一个​​元素,并且数组足够大,则结果指向一个元素与原始元素的偏移量,使得结果和原始元素的下标之差数组元素等于积分表达式.[...] 如果指针操作数和结果都指向同一个数组对象的元素,或者数组对象的最后一个元素之后,评估不会产生溢出;否则,行为未定义.

When an expression that has integral type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integral expression. [...] 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.

为了完整起见,5.2.1 Subscripting1 说:

For completeness sake, section 5.2.1 Subscripting paragraph 1 says:

[...]表达式E1[E2](根据定义)等同于*((E1)+(E2)) [注:详情见5.3和5.7 * 和 + 以及 8.3.4 的数组细节.——结尾说明]

[...]The expression E1[E2] is identical (by definition) to *((E1)+(E2)) [ Note: see 5.3 and 5.7 for details of * and + and 8.3.4 for details of arrays. —end note ]

需要注意的是,编译器不需要为未定义的行为生成警告(诊断),1.4 部分中的 C++ 标准草案实现合规1说:

It is important to note that the compiler is not required to produce a warning(diagnostic) for undefined behavior, the draft C++ standard in section 1.4 Implementation compliance paragraph 1 says:

可诊断规则集包含本国际标准中的所有句法和语义规则除了那些包含无需诊断"或被描述为导致未定义行为"的明确符号的规则.

The set of diagnosable rules consists of all syntactic and semantic rules in this International Standard except for those rules containing an explicit notation that "no diagnostic is required" or which are described as resulting in "undefined behavior."

这篇关于在 C 和 C++ 中访问超出限制的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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