ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-09-18 17:15:37  阅读:247  来源: 互联网

标签:c-3 c arrays undefined-behavior


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有