我发现这个页面,它说明了悬空指针的常见创建方式。
下面的代码用于说明通过返回局部变量的地址来创建悬空指针:
在运行此代码时,我得到了编译器警告(如预期的那样):
然而,当我注释掉fflush(stdout)这一行时,我得到的输出结果如下(与同一编译器警告一样):
这种行为的原因是什么?fflush命令的存在/不存在如何导致这种行为变化?
下面的代码用于说明通过返回局部变量的地址来创建悬空指针:
// 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
是无关紧要的。(fflush
会清空stdout
的内容,但由于您没有缓冲区,它没有任何合法的目的)。您可能会得到5
,您可能会得到一个Segmentation Fault
,这是未定义的。 - David C. Rankin