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];
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];
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:
bbum source share