如何警告超出范围的局部变量的指针 [英] How to be warned about pointers to out-of-scope local variables

查看:187
本文介绍了如何警告超出范围的局部变量的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#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中范围外的局部变量的指针,因此它实际上会调用未定义的行为.如何在代码库中找到此问题的实例?到目前为止,这是我尝试过的:

The intent seems to be that it will print 5, but it actually invokes undefined behavior, due to dereferencing a pointer to an out-of-scope local variable in main. How can I find instances of this problem in a codebase? Here's what I've tried so far:

  • 使用gcc -Wall -Wextra -pedantic
  • 进行编译
  • 使用clang -Weverything
  • 进行编译
  • 运行时已使用clang -fsanitize=undefined
  • 进行了编译
  • valgrind
  • 下运行
  • Compiling with gcc -Wall -Wextra -pedantic
  • Compiling with clang -Weverything
  • Running having compiled with clang -fsanitize=undefined
  • Running under valgrind

以上均未产生任何警告.

None of the above produced any warnings.

推荐答案

首先使用GCC 7.2和在没有 -fsanitize=address 的情况下进行编译,然后在Valgrind下运行会产生以下结果:

Compiling first with GCC 7.2 and without -fsanitize=address and then running under Valgrind produces the following:

==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)

其次是其他警告.

这篇关于如何警告超出范围的局部变量的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆