Click here to Skip to main content
13,189,324 members (65,904 online)
Rate this:
Please Sign up or sign in to 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 19-Jan-13 21:43pm
Updated 19-Jan-13 21:45pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

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:

Call function
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
The variables have been allocated on the stack ("V" and the sp moved)

After function
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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web01 | 2.8.171016.2 | Last Updated 20 Jan 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100