返回指向本地结构的指针

ran*_*guy 4 c variables struct pointers return

将指针返回到C中的本地结构是否安全?我的意思是这样做


struct myStruct* GetStruct()  
{  
    struct myStruct *str = (struct myStruct*)malloc(sizeof(struct myStruct));  
    //initialize struct members here  
    return str;
}  
Run Code Online (Sandbox Code Playgroud)

安全?
谢谢.

bbu*_*bum 13

在您的代码中,您没有返回指向本地结构的指针.您正在返回一个指向malloc()的缓冲区的指针,该缓冲区将驻留在堆上.

因此,非常安全.

但是,调用者(或调用者的调用者或调用者的调用者的被调用者,你明白了)将负责调用free().

这是不安全的:

char *foo() {
     char bar[100];
     // fill bar
     return bar;
}
Run Code Online (Sandbox Code Playgroud)

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

Tinkertim指的是"静态分配标准并提供互斥".

当然:

char *foo() {
    static char bar[100];
    // fill bar
    return bar;
}
Run Code Online (Sandbox Code Playgroud)

这将起作用,它将返回指向静态分配的缓冲区的指针.静态分配意味着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];
Run Code Online (Sandbox Code Playgroud)