返回指针指向一个局部结构 [英] Returning pointer to a local structure

查看:102
本文介绍了返回指针指向一个局部结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it safe to return the pointer to a local struct in C? I mean is doing this


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

安全吗?

谢谢你。

safe?
Thanks.

推荐答案

在您的code,不必返回一个指向一个局部结构。您正在返回一个指向一个malloc()处理缓冲区将驻留在堆。

In your code, you aren't returning a pointer to a local structure. You are returning a pointer to a malloc()'d buffer that will reside upon the heap.

因此​​,完全安全的。

Thus, perfectly safe.

但是,主叫方(或主叫方呼叫方或主叫方的主叫方的被叫方,你的想法),那么将负责调用free()。​​

However, the caller (or the caller's caller or the caller's caller's callee, you get the idea) will then be responsible for calling free().

什么是不安全的是:

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

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

As that returns a pointer to a chunk of memory that is on the stack -- is a local variable -- and, upon return, that memory will no longer be valid.

Tinkertim指的是静态分配的酒吧,并提供相互排斥。

Tinkertim refers to "statically allocating bar and providing mutual exclusion".

当然:

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

这将工作,它会返回一个指向静态分配的缓冲区吧。静态分配意味着,酒吧是一个全球性的。

This will work in that it will return a pointer to the statically allocated buffer bar. Statically allocated means that bar is a global.

因此​​,上面会的的在多线程环境中工作,其中有可能是并发调用富()。您将需要使用某种类型的同步原语,以确保两次调用富()不践踏对方。还有很多很多,同步原语和放大器;可用的模式 - 这与事实问题是关于组合的malloc() ED缓冲提出这样的讨论超出范围了这个问题。

Thus, the above will not work in a multi-threaded environment where there may be concurrent calls to foo(). You would need to use some kind of synchronization primitive to ensure that two calls to foo() don't stomp on each other. There are many, many, synchronization primitives & patterns available -- that combined with the fact that the question was about a malloc()ed buffer puts such a discussion out of scope for this question.

需要明确的是:

// 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];

这篇关于返回指针指向一个局部结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆