Main Content

Allocation of memory for objects in C++ - Stack v Heap

Archive - Originally posted on "The Horse's Mouth" - 2015-10-31 09:16:18 - Graham Ellis

In C++, memory is allocated to variables on a stack or on a heap. Allocated on the stack, the variable persists until the end of the block in which it's defined. Allocated on the heap, the memory containing the object persists until the end of your program, or until you delete the object.

Stack memory is set up by a simple variable declaration as shown in the example:

  Train * serviceStack() {
    Train later(3,79);
    cout << "Created with capacity of " << later.getCapacity() << endl;
    return &later;
    }


And heap memory through the use of the new keyword:

  Train * serviceHeap() {
    Train * early = new Train(2,75);
    cout << "Created with capacity of " << early->getCapacity() << endl;
    return early;
    }


The stack example here is very, very bad indeed as the returned address points to memory on the stack which will be re-used in subsequent code as the program progresses after the return from the function.

Here's code calling our functions above:

  Train * first = serviceHeap();
  Train * second = serviceStack();
  
  int e = first->getCapacity();
  cout << "Capacity of " << e << endl;
  
  int c = second->getCapacity();
  cout << "Capacity of " << c << endl;


and the result of running that code:

  Created with capacity of 210
  Created with capacity of 331
  Capacity of 210
  Capacity of -678813632


Within the methods used to create the objects, teh references to the getCapacity method both return the correctly calculated value. Once the creating methods have been exited, the object that's on the heap (the first one) continues to exist and function correctly, whereas the object that wason the stack has pobably been overwritten with something else, and results are "random". Run it again:

  Created with capacity of 210
  Created with capacity of 331
  Capacity of 210
  Capacity of -395132864


Many modern compilers will flag a warning if they spot you coding in this way:

  WomanWithCat:harwell grahamellis$ g++ -o objects_bothways objects_bothways.cpp
  objects_bothways.cpp:26:10: warning: address of stack memory associated with local variable
    'later' returned [-Wreturn-stack-address]
      return &later;
              ^~~~~
  1 warning generated.
  WomanWithCat:harwell grahamellis$


General rule:

Stack variables for temportary objects, heap for persistant ones

Source code of full example [here]. Subject covered on our Learning to program in C++ amd C++ programming courses.