为什么ptr没有变成悬空指针,因为当返回指针存储局部变量的地址时,返回功能后会被销毁?

发布于 2025-01-21 23:16:47 字数 609 浏览 4 评论 0原文

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮烟 2025-01-28 23:16:47

因为实际上没有任何强制执行您以前的堆栈框架所在的内存位置被覆盖或摧毁。指示指示的内存仍然属于您的应用程序,并且可能坐在那里。

您在这里调用的是不确定的行为,它可能会做不可预测的事情,包括当不被“假定”的工作时进行工作。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文