将指针返回到 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;
}
因为它返回一个指向堆栈上的一块内存的指针——是一个局部变量——并且在返回时,该内存将不再有效。
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];
可以这样想:如果分配给该指针的内存不是该函数的本地内存(即在该函数的该实例的堆栈帧上 - 准确地说),您可以从该函数返回一个指针