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

标签 c pointers variables struct return

在 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/51681615/

相关文章:

c++ - siginfo 匿名 union 体

c - 尝试交换用户输入数组中的多个值

C 拆分指针数组并保存在新变量中

c - ptr*** 不工作

c++ - 无效指针?

php - 在 PHP 中反向堆叠变量

javascript - 如何将 javascript 变量从 php 传递回 javascript

c - strtof() 在 C 中产生奇怪的结果

c - 来自 C++ Reference 的 fread 示例

python - Cython - 替换 def __init__() 方法,因为 Cython 的 Python 函数和方法无法处理值为 0 的无符号字符数组