Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Throughout my inquiries into the workings of C++ compiler i keep
seeing the references to the fact that function variables are deallocated
after execution. Is this deallocation on stack or heap level? Is there
such a thing as dynamic variables within a stack? (from compiler's perspective)

Thank You
Posted
Updated 19-Jan-13 21:45pm
v2

1 solution

With C++ (and C before it) all variables are stack based, unless they are directly allocated from the heap with a malloc (old style) or new (preferable) - in which case you must use the appropriate delete or free method when you are finished with it.

There is no such thing as "dynamic" variables on the stack, since the variable space a function used can be calculated at compile time - dynamic allocation only happens with the heap.

Stack based variables are automatically deallocated when the function exits, because the stack is then freed for the next function to use it:

Maybe a little diagram will help: "x" is used stack, "f" is free. "sp" is the stack pointer - the next free memory
Stack before function call:
xxxxxxxxffffffffffffffff
sp------^


Call function
xxxxxxxxRfffffffffffffff
sp-------^
Now, the Return address has been stacked ("R" - the place in your code from which the function was called) and the sp has moved to the next free location

In function with variables
xxxxxxxxRVVVVfffffffffff
sp-----------^
The variables have been allocated on the stack ("V" and the sp moved)

After function
xxxxxxxxrvvvvfffffffffff
sp------^
The sp has moved back before the return address and all the variables have been deallocated - but not changed in memory, which is why I changed them to lower case.

When the next function is called, the same process happens and the memory is re-used.

That is why hanging references are a PITA - if you return a pointer to a stack based variable, it is still a valid pointer, and teh memory will work - but it can also be used for something else and you end up corrupting memory.
 
Share this answer
 
Comments
Eddie Jordan 20-Jan-13 4:28am    
Thanks! That explains it. I feel kinda bad for not seeing it immediately since I went over this when i learned x86 assembly :P
OriginalGriff 20-Jan-13 4:47am    
Easy to forget - I learned this (the hard way) when I learnt Z80 if it's any consolation! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900