Return pointer to local structure

Is it safe to return a pointer to a local structure in C? I mean do it

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

safely?
Thanks.

+4
source share
2 answers

In your code, you are not returning a pointer to a local structure. You are returning a pointer to the malloc () 'd buffer, which will be on the heap.

Thus, it is completely safe.

However, the caller (or the caller or the caller, you get this idea) will be responsible for calling free ().

Which is unsafe:

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

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

Tinkertim refers to "static distribution of the bar and providing mutual exclusion."

Sure:

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

This will work as it will return a pointer to a statically allocated buffer bar. Static highlighting means the bar is global.

Thus, the above will not work in a multi-threaded environment where there may be simultaneous calls to foo() . You will need to use some kind of synchronization primitive so that two calls to foo() do not stomp on each other. There are many, many synchronization primitives and templates available, which, combined with the fact that the question was about the malloc() ed buffer, gives 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]; 
+13
source

Think of it this way: you can return a pointer from a function if the memory allocated to this pointer is not local to this function (i.e., to be exact in the stack frame of this instance of this function)

+2
source

All Articles