返回一个指向自动变量 [英] Returning a pointer to an automatic variable

查看:117
本文介绍了返回一个指向自动变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有以下功能:

char *getp()
{
    char s[] = "hello";
    return s;
}

由于函数是在函数返回一个指针到一个局部变量来使用外,它会导致内存泄漏?

Since the function is returning a pointer to a local variable in the function to be used outside, will it cause a memory leak?

P.S。我仍然在学习C所以我的问题可能有点天真...

[更新]

所以,如果说你要返回一个新的的char [] 阵列(即也许对于一个子功能),你怎么只返回?它应该是指向一个外部变量?即的char [] 不在本地的功能?

[Update]
So, if say you want to return a new char[] array (ie maybe for a substring function), what do you return exactly? Should it be pointer to an external variable ? ie a char[] that is not local to the function?

推荐答案

这不会导致内存泄漏。它会导致悬挂引用。局部变量是在栈中分配,并会尽快,因为它超出范围释放。其结果是,当函数结束时,指针,你正在返回不再指向你自己的记忆。这不是一个内存泄漏(内存泄漏是当你分配一些内存,并且不释放它)。

It won't cause a memory leak. It'll cause a dangling reference. The local variable is allocated on the stack and will be freed as soon as it goes out of scope. As a result, when the function ends, the pointer you are returning no longer points to a memory you own. This is not a memory leak (memory leak is when you allocate some memory and don't free it).

[更新]
为了能够返回一个函数分配的数组,你应该分配它之外的堆栈(例如,在堆),如:

[Update]: To be able to return an array allocated in a function, you should allocate it outside stack (e.g. in the heap) like:

char *test() {
    char* arr = malloc(100);
    arr[0] = 'M';
    return arr;
}

现在,如果你不免费在调用函数的内存,你使用它后完成后,你有内存泄漏。

Now, if you don't free the memory in the calling function after you finished using it, you'll have a memory leak.

这篇关于返回一个指向自动变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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