views:

589

answers:

2

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.

+12  A: 

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.

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().

What isn't safe is this:

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 refers to "statically allocating bar and providing mutual exclusion".

Sure:

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.

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.

To be clear:

// 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];
bbum
+1 , though you might consider revising the unsafe example to be safe, by statically allocating bar[] and indicating the need for mutual exclusion when calling the function. That would make this answer very helpful in the archive.
Tim Post
Just to be clear: malloc, like new, allocates space in heap and not stack? Did I get it right?
Amarghosh
Thanks. I get confused with stack and heaps every now and then.
random_guy
Good explanation, but maybe the examples would be better if replacing the arrays with actual structs (and returning the pointer), as in the question?
ahy1
+2  A: 

Think of it this way: You can return a pointer from a function if the memory allocated to that pointer is not local to that function (i.e. on the stack frame of that instance of that function - to be precise)

Ashwin