returning a local variable from function in C [duplicate] returning a local variable from function in C [duplicate] c c

returning a local variable from function in C [duplicate]


The issue here is that when you create the local variable it is allocated on the stack and is therefore unavailable once the function finishes execution (implementation varies here). The preferable way would be to use malloc() to reserve non-local memory. the danger here is that you have to deallocate (free()) everything you allocated using malloc(), and if you forget, you create a memory leak.


For foo1(), you return a copy of the local variable, not the local variable itself.

For the other functions, you return a copy of a pointer to a local variable. However, that local variable is deallocated when the function finishes, so you end up with nasty issues if you try to reference it afterwards.


Any variable has some space in the memory. A pointer references that space. The space that local variables occupies is deallocated when the function call returns, meaning that it can and will be reused for other things. As a consequence, references to that space are going to wind up pointing to something completely unrelated. Arrays in C are implemented as pointers, so this winds up applying to them. And constant arrays declared in a function also count as being local.

If you want to use an array or other pointer beyond the scope of the function in which it is created, you need to use malloc to reserve the space for it. Space reserved using malloc will not be reallocated or reused until it is explicitly released by calling free.