考虑以下代码:
#include <stdio.h>
void badidea(int**);
int main(void) {
int* p;
badidea(&p);
printf("%d\n", *p); /* undefined behavior happens here: p points to x from badidea, which is now out of scope */
return 0;
}
void badidea(int** p) {
int x = 5;
*p = &x;
}
它的意图似乎是它会打印 5
,但它实际上调用了未定义的行为,因为在 main
中取消了指向范围外局部变量的指针>。如何在代码库中找到此问题的实例?到目前为止,这是我尝试过的:
- 使用
gcc -Wall -Wextra -pedantic
编译 - 使用
clang -Weverything
编译 - 使用
clang -fsanitize=undefined
编译后运行 - 在
valgrind
下运行
以上均未产生任何警告。
最佳答案
首先使用 GCC 7.2 编译,没有 -fsanitize=address
and 然后在 Valgrind 下运行产生以下结果:
==25751== Conditional jump or move depends on uninitialised value(s)
==25751== at 0x4E988DA: vfprintf (vfprintf.c:1642)
==25751== by 0x4EA0F25: printf (printf.c:33)
==25751== by 0x1086E5: main (in ./a.out)
后跟其他警告。
关于c - 如何警告指向超出范围的局部变量的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52601540/