为什么即使要求,gcc也不会抱怨数组边界? [英] Why isn't gcc complaining about array bounds even if requested?
问题描述
我正在使用gcc 4.9.0,并且我希望看到编译器警告我有关超出数组范围的问题。如果我对此进行编译
I'm using gcc 4.9.0 and I would like to see compiler warn me about exceeded array bounds. If I compile this
int main()
{
int table[5]={0};
table[8] = 1234;
int x = table[10];
}
with g ++ -O2 -Wall main.cpp -o main.exe仅我得到有关未使用的x的警告:
with g++ -O2 -Wall main.cpp -o main.exe I only get warning about unused 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 )我看到-O2与-Wall一起应启用-Warray-bounds = 1检查。如果我尝试添加-Warray-bounds,情况不会改变。实际上,编译器甚至无法识别-Warray-bounds = 1:
From gcc documentation (https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#Warning-Options) I see that -O2 together with -Wall should enable -Warray-bounds=1 check. Things don't change if I try to add -Warray-bounds. As a matter of fact, the compiler doesn't even recognize -Warray-bounds=1:
g++: error: unrecognized command line option '-Warray-bounds=1'
现在,为什么编译器不给出任何警告错误地写入/读取数组?为何编译器无法识别‘-Warray-bounds = 1’?
Now, why doesn't compiler give any warning about incorrectly writing into / reading from the array? And why doesn't the compiler recognize '-Warray-bounds=1'?
推荐答案
编译器可能对其进行了优化。尝试制作表
易失性
。
Probably compiler optimizes it away. Try making table
volatile
.
int main()
{
volatile int table[]={0,0};
table[8] = 1234;
int x = table[10];
}
产生:
prog.cc:4:12: warning: array subscript is above array bounds [-Warray-bounds]
table[8] = 1234;
~~~~~~~^
prog.cc:5:21: warning: array subscript is above array bounds [-Warray-bounds]
int x = table[10];
~~~~~~~~^
这里是 实时示例 。
来自 -Warray-bounds
docs:
它警告数组的下标始终超出范围
It warns about subscripts to arrays that are always out of bounds
我的猜测是g ++决定在访问从未真正发生时不发出警告。
My guess is that g++ decides not to warn when the access never actually happens.
事实上,编译器甚至无法识别-Warray-bounds = 1:
As a matter of fact, the compiler doesn't even recognize -Warray-bounds=1:
g ++:错误:无法识别命令行选项'-Warray-bounds = 1'
g ++-4.9.0不支持格式为 -Warray-bounds = n
,但在 -Warray-bounds
上也可以正常工作。 g ++-5.1.0支持 -Warray-bounds = n
。
g++-4.9.0 does not support command in the format -Warray-bounds=n
, but it will work just fine with -Warray-bounds
. -Warray-bounds=n
is supported from g++-5.1.0.
这篇关于为什么即使要求,gcc也不会抱怨数组边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!