When are variables removed from memory in C++?

10,781

Solution 1

The local variable temp is "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:

int addTwo(int num)
{
00411380  push        ebp  
00411381  mov         ebp,esp             //Store current stack pointer
00411383  sub         esp,0CCh            //Reserve space on stack for locals etc
00411389  push        ebx  
0041138A  push        esi  
0041138B  push        edi  
0041138C  lea         edi,[ebp-0CCh] 
00411392  mov         ecx,33h 
00411397  mov         eax,0CCCCCCCCh 
0041139C  rep stos    dword ptr es:[edi] 
    int temp = 2;
0041139E  mov         dword ptr [temp],2 
    num += temp;
004113A5  mov         eax,dword ptr [num] 
004113A8  add         eax,dword ptr [temp] 
004113AB  mov         dword ptr [num],eax 
    return num;
004113AE  mov         eax,dword ptr [num] 
}
004113B1  pop         edi  
004113B2  pop         esi  
004113B3  pop         ebx  
004113B4  mov         esp,ebp                 //Restore stack pointer
004113B6  pop         ebp  
004113B7  ret        

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.

Solution 2

In C++ there is a very simple rule of thumb:

All memory is automatically freed when it runs out of scope unless it has been allocated manually.

Manual allocations:

  • Any object allocated by new() MUST be de-allocated by a matching delete().
  • Any memory allocated by malloc() MUST be de-allocated by a matching free().

A very useful design pattern in C++ is called RAII (Resource Acquisition Is Initialization) which binds dynamic allocations to a scoped object that frees the allocation in its destructor.

In RAII code you do not have to worry anymore about calling delete() or free() because they are automatically called whenever the "anchor object" runs out of scope.

Solution 3

Here, temp is allocated on the stack, and the memory that it uses is automatically freed when the function exits. However, you could allocate it on the heap like this:

int *temp = new int(2);

To free it, you have to do

delete temp;

If you allocate your variable on the stack, this is what typically happens:

When you call your function, it will increment this thing called the 'stack pointer' -- a number saying which addresses in memory are to be 'protected' for use by its local variables. When the function returns, it will decrement the stack pointer to its original value. Nothing is actually done to the variables you've allocated in that function, except that the memory they reside in is no longer 'protected' -- anything else can (and eventually will) overwrite them. So you're not supposed to access them any longer.

If you need the memory allocated to persist after you've exited the function, then use the heap.

Solution 4

Its not removed from memory once the function exits.

It remains in memory, in addTwo's stack frame, until some other process (or the same) re uses that portion of memory.

Until that point, accessing temp is undefined behaviour.

Solution 5

temp is allocated on the stack. So when the function returns, it is gone.

C++ scope rules are similar to C#.

Share:
10,781
jmasterx
Author by

jmasterx

Hi

Updated on June 18, 2022

Comments

  • jmasterx
    jmasterx almost 2 years

    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