C/C++Stack Variables

Most languages like Python, Lua, Java and C# only give you the choice of allocating memory for objects in one way - namely on the heap and they use memory garbage collection. C++ allows the choice of using the heap or the stack.

Heap Allocation

Objects allocated on the heap are allocated via the 'new' keyword or underneath the hood using 'malloc'. i.e.

FOOfoo* pFoo = new FOOfoo();

The lifetime of heap variables is for as long as you need them. With heap variables the programmer needs to explicitly give the memory back to the operating system at some point by invoking delete (or free()). i.e.

delete pFoo;

If program doesn't do this reliably we get a memory leak.

The operating system allocates memory using malloc which typically has an implementation which keeps a linked list of available memory blocks and parcels them out to the applications as required.

Stack Variables

C++ is unusual in that it gives the programmer the option of creating variables on the 'stack'. The stack is a block of memory that every thread in a program has.

When we call a function underneath the hood basically variables are pushed on to the stack by the caller of a function before the function is called.

C++ allows objects to be have the memory allocated for them on the stack which means as we return from each function context they must be deallocated. i.e. the any stack variable will be destroyed when we exit the stack frame that it was created in, i.e.:

void main(){ { int A; // stack variable A = 10; } // A goes out of scope for the stack and is destroyed. { double A; // another stack variable A = 1.0; } // A goes out of scope for the stack and is destroyed // The next line is illegal because A does not exist in this stack frame COLcout << A; }

One of the gotchas with stack variables is a mistake of returning a reference to a temporary stack variable. The compiler will often let you do it but the result is mysterious intermittent memory corruption. This code example shows the problem:

In the first case the Temp stack variable has gone out of scope and so it’s not guaranteed what will in the memory that the COLstring was using. Downstream one will see memory corruption.

In the second case the following sequence happens:

  • A new temporary COLstring is created - but in the stack scope of the caller to the method

  • It uses the copy constructor to copy the data from temporary stack variable.

  • Then it doesn’t matter when the Temp stack variable string goes out of scope and is destroyed.