gpt4 book ai didi

c - 返回指向局部结构的指针

转载 作者:太空狗 更新时间:2023-10-29 15:12:43 26 4
gpt4 key购买 nike

在 C 中返回指向局部结构的指针是否安全?我的意思是这样做


struct myStruct* GetStruct()
{
struct myStruct *str = (struct myStruct*)malloc(sizeof(struct myStruct));
//initialize struct members here
return str;
}

安全吗?
谢谢。

最佳答案

在您的代码中,您没有返回指向局部结构的指针。您正在返回指向将驻留在堆上的 malloc() 缓冲区的指针。

因此,绝对安全。

但是,调用者(或调用者的调用者或调用者的调用者的被调用者,你懂的)将负责调用 free()。

这是不安全的:

char *foo() {
char bar[100];
// fill bar
return bar;
}

因为它返回指向堆栈上一 block 内存的指针——是一个局部变量——并且在返回时,该内存将不再有效。

Tinkertim 是指“静态分配 bar 并提供互斥”。

当然:

char *foo() {
static char bar[100];
// fill bar
return bar;
}

这将起作用,因为它将返回一个指向静态分配的缓冲区栏的指针。静态分配意味着 bar 是全局的。

因此,上面的代码将不能在可能同时调用foo() 的多线程环境中工作。您需要使用某种同步原语来确保对 foo() 的两次调用不会相互干扰。有许多可用的同步原语和模式——再加上问题是关于 malloc()ed 缓冲区这一事实,使得此类讨论超出了该问题的范围。

要清楚:

// this is an allocation on the stack and cannot be safely returned
char bar[100];

// this is just like the above; don't return it!!
char *bar = alloca(100);

// this is an allocation on the heap and **can** be safely returned, but you gotta free()
malloc(100);

// this is a global or static allocation of which there is only one per app session
// you can return it safely, but you can't write to it from multiple threads without
// dealing with synchronization issues!
static char bar[100];

关于c - 返回指向局部结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1475635/

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