c - 如何警告指向超出范围的局部变量的指针

标签 c pointers compiler-warnings undefined-behavior static-analysis

考虑以下代码:

#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/

相关文章:

c - 没有编译错误,但给定输入时崩溃

c - 将零参数函数添加到 _Generic 宏

c - 空指针是否间接指向数组类型 UB?

c - 堆栈在c中存储结构指针

c++ - 忽略 gcc/clang 的 "-Wmissing-braces"警告是否明智?

c - 如果 C 有指针,为什么它需要数组?

c - 为什么 char 数组的两个元素的内存地址差异为 4?

c++ - c++ 指针在此代码中的作用

c++ - 我可以让 GCC 在将太宽的类型传递给函数时发出警告吗?

java - 关闭 javac 警告