Returning references to local variables from a function in c
2 min read
You might have read and experienced that you can either return the value itself or the pointers to global objects. However, you cannot return references to any of the local variables. If you have wondered why, then you are about to read the reason and process to return local references.
If you don’t know, there are two kinds of memory assigned to a program in run-time
heap. Stacks are maintained by subconscious part of you program setup
during compilation; or for interpreted languages like Ruby the interpreter takes care of it.
!(<%= current_page.data.heap_stack %>)
Basically, when you call a function in
C, all the data like
local vars defined and
function arguments are store in the stack . Whenever the program execution/flow comes
out of the function i.e. return is triggered, all the local data are popped out of the
meaning, they no longer exist. Stacks are volatile you see. This is the reason
C does not
allow you to
return the references to objects that are no longer gonna be available.
Can we return pointers to local vars?
Yes! we can. If you have noticed, the only thing stopping you returning references is the
unavailability (stored in
stacks). How about storing your data in
Heap does not flush just after the function dies; it lives till your program dies.
You will have to free up the memory once you are done though, using free method. Please feel free to comment in case of any mistakes and typos.