为什么这个函数返回值的垃圾 [英] why does this function return garbage value

查看:225
本文介绍了为什么这个函数返回值的垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个程序,并面临这样的问题,所使用的下列函数返回垃圾值:

I was writing a program and facing this problem that the following function used to return garbage values:

int* foo(int temp){
   int x = temp;
   return &x;
}

当我修改了它这个,它工作得很好:

When I modified it to this, it worked fine:

int* foo(int *temp){
    int *x = temp;
    return x
}

什么是错的第一个版本?

What was wrong with the first version?

推荐答案

第一个版本恢复到一个局部变量的引用 X ,其存储是仅限于功能。当函数退出, X 不能再被使用。返回对它的引用是一个实例中的悬摆指针

The first version returns a reference to a local variable x whose storage is limited to the function foo. When the function exits, x can no longer be used. Returning a reference to it is one instance of a dangling pointer.

在第二个版本,你真的只传递和返回同样的指针值,它指的是内存,不是的由函数的寿命限制。因此,即使该函数退出后,返回的地址仍然有效。

In the second version, you're really only passing in and returning the same pointer value, which refers to memory which isn't limited by the lifetime of the function. So even after the function exits, the returned address is still valid.

另一种选择:

int *foo(int temp)
{
    int *x = malloc(sizeof(int));
    *x = temp;
    return x;
}

这篇关于为什么这个函数返回值的垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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