为什么不编译器警告超出界限静态数组的索引? [英] Why do compilers not warn about out-of-bounds static array indices?

查看:157
本文介绍了为什么不编译器警告超出界限静态数组的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一位同事最近已经完成写出界的堆栈上的静态数组严重咬伤(他添加的元素它不增加数组的大小)。不应编译器捕获这种类型的错误?下面code使用gcc编译干净,甚至与 -Wall -Wextra 选项,但它显然是错误的:

A colleague of mine recently got bitten badly by writing out of bounds to a static array on the stack (he added an element to it without increasing the array size). Shouldn't the compiler catch this kind of error? The following code compiles cleanly with gcc, even with the -Wall -Wextra options, and yet it is clearly erroneous:

int main(void)
{
  int a[10];
  a[13] = 3;  // oops, overwrote the return address
  return 0;
}

我敢肯定,这是不确定的行为,虽然我不能找到C99标准在目前这样说的摘录。但在最简单的情况,其中一个阵列的大小被称为编译时间和指数是在编译时已知的,不应当编译器至少是发出警告

I'm positive that this is undefined behavior, although I can't find an excerpt from the C99 standard saying so at the moment. But in the simplest case, where the size of an array is known as compile time and the indices are known at compile time, shouldn't the compiler emit a warning at the very least?

推荐答案

GCC的的警告这一点。但是,你需要做两件事情:

GCC does warn about this. But you need to do two things:


  1. 启用优化。如果没有至少-O2,海湾合作委员会没有采取足够的分析知道什么 A 就是和你跑了边缘。

  2. 更改您的例子,这样一个[]实际使用,否则GCC产生一个​​无操作方案,并已经完全抛弃你的任务。

  1. Enable optimization. Without at least -O2, GCC is not doing enough analysis to know what a is, and that you ran off the edge.
  2. Change your example so that a[] is actually used, otherwise GCC generates a no-op program and has completely discarded your assignment.

$ cat foo.c 
int main(void)
{
  int a[10];
  a[13] = 3;  // oops, overwrote the return address
  return a[1];
}
$ gcc -Wall -Wextra  -O2 -c foo.c 
foo.c: In function ‘main’:
foo.c:4: warning: array subscript is above array bounds

BTW:如果你返回你的测试程序[13],这将不能工作,因为GCC再次优化了阵列

BTW: If you returned a[13] in your test program, that wouldn't work either, as GCC optimizes out the array again.

这篇关于为什么不编译器警告超出界限静态数组的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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