为什么ptr没有变成悬空指针,因为当返回指针存储局部变量的地址时,返回功能后会被销毁?
#include<stdio.h>
int *func(int * ptr){
int a = 12;
int *c = &a;
return c; // here it returns the pointer by storing the address of local variable
}
int main()
{
int *ptr = NULL;
ptr= func(ptr); // here the address is stored but the local variable gets destroyed
printf("the value is %d\n",*ptr); // So how can it print the value 12 here if local variable gets destroyed or did I miss something?
return 0;
}
输出,
The valus is 12
但是如何可能,因为当它通过将地址存储在指针中时,变量会破坏,因此PTR变为悬挂,但仍然可以提供输出12。
#include<stdio.h>
int *func(int * ptr){
int a = 12;
int *c = &a;
return c; // here it returns the pointer by storing the address of local variable
}
int main()
{
int *ptr = NULL;
ptr= func(ptr); // here the address is stored but the local variable gets destroyed
printf("the value is %d\n",*ptr); // So how can it print the value 12 here if local variable gets destroyed or did I miss something?
return 0;
}
Output
The valus is 12
But how it is possible because when it returns the address by storing it in the pointer the variable get destroy so ptr becomes dangle but it still gives output 12.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为实际上没有任何强制执行您以前的堆栈框架所在的内存位置被覆盖或摧毁。指示指示的内存仍然属于您的应用程序,并且可能坐在那里。
您在这里调用的是不确定的行为,它可能会做不可预测的事情,包括当不被“假定”的工作时进行工作。
Because nothing actually enforces that the memory location your previous stack frame was in gets overwritten or destroyed. The memory where your pointer was declared still belongs to your application, and is probably sitting there untouched.
What you've invoked here is undefined behavior which may do unpredictable things, including work when it's not "supposed" to.