我正在使用 gcc 4.9.0,我希望看到编译器警告我超出数组范围。如果我编译这个
int main()
{
int table[5]={0};
table[8] = 1234;
int x = table[10];
}
使用 g++ -O2 -Wall main.cpp -o main.exe 我只收到有关未使用的 x 的警告:
main.cpp: In function 'int main()':
main.cpp:8:7: warning: unused variable 'x' [-Wunused-variable]
int x = table[10];
^
来自 gcc 文档 (https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options)我看到 -O2 与 -Wall 一起应该启用 -Warray-bounds=1 检查。如果我尝试添加 -Warray-bounds ,事情不会改变。事实上,编译器甚至无法识别 -Warray-bounds=1:
g++: error: unrecognized command line option '-Warray-bounds=1'
现在,为什么编译器不给出任何有关错误写入/读取数组的警告?为什么编译器不能识别“-Warray-bounds=1”?
我怀疑缺少警告是因为优化。编译器很容易看出您编写的任何行都不会影响程序的行为,因此可能选择简单地跳过这些行。
看起来检查已知越界访问的编译时间的阶段恰好是在删除未使用的代码之后执行的,因此 GCC 从未发现您的错误。
防止这种优化的一个简单方法是声明数组volatile
。任何写入或读取volatile
对象必须被编译器视为副作用,因此无法优化掉。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)