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