I’ve been using C++ for a bit now. I’m just never sure how the memory management works, so here it goes:
I’m first of all unsure how memory is unallocated in a function, ex:
int addTwo(int num)
{
int temp = 2;
num += temp;
return num;
}
So in this example, would temp be removed from memory after the function ends? If not, how is this done. In C# a variable gets removed once its scope is used up. Are there also any other cases I should know about?
Thanks
The local variable
tempis “pushed” on a stack at the beginning of the function and “popped” of the stack when the function exits.Here’s a disassembly from a non optimized version:
The terms “pushed” and “popped” are merely meant as an analogy. As you can see from the assembly output the compiler reserves all memory for local variables etc in one go by subtracting a suitable value from the stack pointer.