我知道它一定在某个地方得到了回答,但我没有找到关于这种奇怪行为的任何信息。我只是在乱搞堆,当我以零优化执行程序时,没有错误。我去了godbolt而且看起来根本没有组装说明。
- 如果只传递
-O
而没有任何级别,代码会发生什么情况? - 这和
-O0
有什么区别,顺便说一句,效果很好?
int main(int argc, char **argv)
{
char* x = malloc(10);
char n = x[11];
}
$ gcc -O -g -fsanitize=address main.c -o main
$ ./main # No problems
gdb) info locals # Without -fsanitize=address
x = <optimized out>
n = <optimized out>
最佳答案
I went to godbolt and it looks like there's no assembly instructions at all
确实,GCC优化掉了你所有的代码,因为你没有以任何方式使用。如果你change it slightly然后它会留在生成的程序集中,AddressSanitizer 会发现堆溢出。
如您所料,以下代码会生成 AddressSanitizer 堆缓冲区溢出错误:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char* x = malloc(10);
char n = x[11];
return n;
}
关于c - gcc -O 优化不检测未使用变量的堆溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72773598/