c - 如何警告指向超出范围的局部变量的指针
问题描述
考虑以下代码:
#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;
}
意图似乎是它会 print 5
,但它实际上调用了未定义的行为,因为取消引用指向 in 中范围外局部变量的指针main
。如何在代码库中找到此问题的实例?这是我到目前为止所尝试的:
- 编译
gcc -Wall -Wextra -pedantic
- 编译
clang -Weverything
- 编译后运行
clang -fsanitize=undefined
- 跑下
valgrind
以上都没有产生任何警告。
解决方案
首先使用 GCC 7.2 编译,然后在 Valgrind下运行 -fsanitize=address
,然后生成以下内容:
==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)
其次是其他警告。
推荐阅读
- android - 获取失败的解决方案:Lorg/apache/http/impl/nio/reactor/DefaultConnectingIOReactor 尝试从 RapidAPI 实现 Unirest API 时
- javascript - 当 SectionList/Flatlist 滚动/渲染项目时 UI 线程似乎被阻塞(React Native)
- scala - 我的 Kafka Producer 代码运行良好,没有任何异常,但没有数据在代理中发送
- oracle - 用主窗体打开多个窗体
- python - 如何使用python中的类在文本文件中进行模式搜索
- php - 在 Laravel 5.7 中以表单形式验证输入数组
- amazon-web-services - JHipster AWS 和默认子网
- mysql - MySQL - 索引创建问题 - 区别在哪里?
- ios - 主题不允许推送通知
- cassandra - Cassandra 密钥空间恢复