访问阵列超越C和C ++的限制 [英] Access array beyond the limit in C and C++

查看:79
本文介绍了访问阵列超越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草案节附件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:

这是数组下标超出范围,即使对象是显然访问
  定标(如在左值前pression一个[1] [7]指定的声明INT
  一个[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 加法运算符的段落的 5 的说道:

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

当具有整体式的前pression加到或从一个指针中减去,其结果具有指针操作数的类型。如果指针操作数指向一个的阵列对象的元素,并且阵列足够大下,结果指向一个元件从原始元件偏移,使得所得到的和原始的标之差数组元素等于积分前pression。 [...]如果这两个指针操作数,在结果指向相同的数组对象的元素,或者一个过去的数组对象的最后一个元素,该评估也不得产生溢出;否则,行为是不确定的。

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 的说道:

For completeness sake, section 5.2.1 Subscripting paragraph 1 says:

[...]这位前pression 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 ]

要注意的是,编译器不需要生成警告(诊断的)未定义行为,部分草案C ++标准 1.4 实施符合的段落的 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天全站免登陆