我遇到了 this page,它说明了创建悬空点的常见方法。

下面的代码用于通过返回局部变量的地址来说明悬空指针:

// The pointer pointing to local variable becomes
// dangling when local variable is static.
#include<stdio.h>

int *fun()
{
    // x is local variable and goes out of scope
    // after an execution of fun() is over.
    int x = 5;

    return &x;
}

// Driver Code
int main()
{
    int *p = fun();
    fflush(stdout);

    // p points to something which is not valid anymore
    printf("%d", *p);
    return 0;
}

在运行它时,这是我得到的编译器警告(如预期):
 In function 'fun':
12:2: warning: function returns address of local variable [-Wreturn-local-addr]
  return &x;
  ^

这是我得到的输出(到目前为止很好):
32743

但是,当我注释掉 fflush(stdout) 行时,这是我得到的输出(具有相同的编译器警告):
5

这种行为的原因是什么? fflush 命令的存在/不存在究竟是如何导致这种行为改变的?

最佳答案

正如您所提到的,返回指向堆栈上对象的指针是不好的。您只看到 fflush() 调用有问题的原因是,如果堆栈不存在,则堆栈未修改。也就是说,5 仍然存在,所以指针解引用仍然给你那个 5。如果你在 funprintf 之间调用一个函数(几乎任何函数,可能),它几乎肯定会覆盖那个堆栈位置,使后来的解引用返回该函数碰巧留在那里的任何垃圾。

关于c - fflush() 在悬空指针方面做了什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43566705/

10-11 22:10
查看更多