gpt4 book ai didi

c - 从另一个函数内部返回本地 malloc() 指针

转载 作者:行者123 更新时间:2023-11-30 18:37:17 24 4
gpt4 key购买 nike

我正在经历一些lecture slides来自普林斯顿大学,有个问题。教授有以下代码片段(在幻灯片 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();

Table_crate() 函数中,即使 t 是使用 malloc 分配的,t 本身也会位于堆栈上,对吗?

那么,你能从这个函数返回t吗?我认为 Table_create() 中的 t 会在函数返回后立即消失。

最佳答案

变量t具有自动存储期限。但这并不妨碍您从函数返回其。值本身(即由 malloc() 返回的指针)具有程序的生命周期(或者直到您对其调用 free() 为止)。所以,这不是问题从函数返回 malloc() 的值。

如果有帮助,请考虑以下内容:

int func(int num)
{
int val;
val = num * 2; // take care of signed integer overflow!
return val;
}

这里返回valval(局部变量,具有自动存储期限)的生命周期有关系吗?不。这类似于您拥有的 malloc() 代码。

关于c - 从另一个函数内部返回本地 malloc() 指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37661454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com