Click here to Skip to main content
11,805,035 members (66,898 online)
Rate this: bad
Please Sign up or sign in to vote.
See more: C++ memory
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
Edited 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 at 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 at 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
0 OriginalGriff 305
1 Sergey Alexandrovich Kryukov 268
2 CPallini 210
3 Richard Deeming 190
4 CHill60 150
0 OriginalGriff 3,255
1 Maciej Los 1,990
2 KrunalRohit 1,907
3 CPallini 1,855
4 Richard MacCutchan 1,227

Advertise | Privacy | Mobile
Web04 | 2.8.151002.1 | Last Updated 20 Jan 2013
Copyright © CodeProject, 1999-2015
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