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

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

问题描述

假设您有以下功能:

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天全站免登陆