首页 > 解决方案 > 如何警告指向超出范围的局部变量的指针

问题描述

考虑以下代码:

#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。如何在代码库中找到此问题的实例?这是我到目前为止所尝试的:

以上都没有产生任何警告。

标签: cpointerscompiler-warningsundefined-behaviorstatic-analysis

解决方案


首先使用 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)

其次是其他警告。


推荐阅读