Dynamic Memory and the Free Store

When to use the stack vs the heap

How do I decide when to allocate memory on the stack versus the heap?

Abstract art representing computer programming

In general, you should prefer allocating memory on the stack when possible. Stack allocation is faster and automatically managed.

Use stack allocation when:

  • The lifetime of the object is tied to the current scope
  • The size of the object is known at compile time and is not too large

Use heap allocation when:

  • The object needs to outlive the current function
  • The size of the object is not known at compile time
  • The size of the object is too large for the stack

Here's an example illustrating both:

#include <iostream>

void func() {
  // Allocated on the stack
  int stackInt = 10;      

  // Allocated on the heap
  int* heapInt = new int(20);

  // We must delete the heap-allocated variable
  delete heapInt;              
}  // stackInt is automatically deallocated here

int main() {
  int size;
  std::cin >> size;

  // Size not known at compile time
  int* array = new int[size];
  delete[] array;
}

Remember, whenever you allocate memory on the heap with new, you are responsible for deallocating it with delete to avoid memory leaks.

In modern C++, you can often avoid making this decision by using standard library containers like std::vector, or smart pointers like std::unique_ptr and std::shared_ptr. These manage memory for you, with the memory for the actual data being allocated on the heap, but the bookkeeping handled automatically.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved