gpt4 book ai didi

c++ - 为什么 gcc 即使被要求也不提示数组边界?

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:04 24 4
gpt4 key购买 nike

我正在使用 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) 我看到 -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 对象的任何写入或读取都必须被编译器视为副作用,因此不能被优化掉。

关于c++ - 为什么 gcc 即使被要求也不提示数组边界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46421326/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com