Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning pointer to a local structure

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.

like image 825
random_guy Avatar asked Sep 25 '09 05:09

random_guy


2 Answers

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];
like image 156
bbum Avatar answered Oct 19 '22 01:10

bbum


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)

like image 37
Ashwin Avatar answered Oct 19 '22 01:10

Ashwin