其他分享
首页 > 其他分享> > 访问超出C和C限制的数组

访问超出C和C限制的数组

作者:互联网

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

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

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

谢谢.

解决方法:

访问数组边界外部是未定义的行为,来自c99 draft standard部分附件J.2 J.2未定义的行为包括以下几点:

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).

第5.7节“添加剂运算符”第5段中的draft C++ standard说:

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节订阅第1段说:

[…]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实施合规性第1节中的草案C标准说:

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-3,c,arrays,undefined-behavior
来源: https://codeday.me/bug/20190918/1811181.html