[英]Returning local malloc() pointer from inside another function
I'm going through some lecture slides from Princeton University and have a question. 我正在浏览普林斯顿大学的一些演讲幻灯片 ,并有一个问题。 The professor has this code snippet (on slide 8 there):
教授有以下代码段(在幻灯片8上):
struct Table *Table_create(void) {
struct Table *t;
t = (struct Table*)malloc(sizeof(struct Table));
t->first = NULL;
return t;
}
struct Table *t;
…
t = Table_create();
…
In the Table_crate()
function, even though t
is allocated using malloc
, t
itself would be located on the stack, correct?. 在
Table_crate()
函数中,即使使用malloc
分配了t
, t
本身也将位于堆栈上,对吗?
So, can you return t
from this function? 那么,您可以从该函数返回
t
吗? I'd think t
in Table_create()
would disappear as soon as the function returns. 我认为
Table_create()
t
将在函数返回时消失。
The variable t
has automatic storage duration. 变量
t
具有自动存储持续时间。 But that doesn't prevent you from returning its value from the function. 但这并不能阻止您从函数中返回其值 。 The value itself (ie the pointer returned by
malloc()
) has the lifetime of the program (or until you call free()
on it). 值本身(即
malloc()
返回的指针)具有程序的生存期(或直到您对其调用free()
为止)。 So, it's not an issue to return the malloc()
'ed value from a function. 因此,从函数返回
malloc()
的值不是问题。
If it helps, consider this: 如果有帮助,请考虑以下事项:
int func(int num)
{
int val;
val = num * 2; // take care of signed integer overflow!
return val;
}
Does returning val
here has anything to do with the lifetime of val
(which is a local variable and has automatic storage duration)? 在这里返回
val
是否与val
的生命周期有关(这是一个局部变量并具有自动存储持续时间)? No. This is analogous to malloc()
code you have. 不。这类似于您拥有的
malloc()
代码。
The variable t
lives on the stack, but the thing it points to (via the call to malloc
) lives on the heap. 变量
t
位于堆栈上,但是它指向的内容(通过调用malloc
)位于堆栈上。
When you return t
you are returning it's value, which is the address on the allocated memory. 当您返回
t
您将返回它的值,即分配的内存上的地址。 This is then assigned to a local variable in the caller. 然后将其分配给调用方中的局部变量。 If you hadn't assigned it in the caller you would have a memory leak.
如果未在调用方中分配它,则可能会发生内存泄漏。 At some point you will need to call
free
in order to release the memory and avoid the memory leak. 在某些时候,您将需要拨打
free
电话以释放内存并避免内存泄漏。
是的,您可以返回存储在 t
的值,因为该值已被复制到调用方,但是您不应返回指向 t
指针或引用,因为t
将会消失并且此类指针或引用是无用的。
t
would not be on the stack. t
不会在堆栈上。 You can return t
from the function. 您可以从函数返回
t
。 malloc
will remember the allocated memory until you call free
malloc
会记住分配的内存,直到您调用free
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.