When to use the stack vs the heap

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

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.

Dynamic Memory and the Free Store

Learn about dynamic memory in C++, and how to allocate objects to it using new and delete

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Should I delete this?
Since I am responsible for memory allocated with new, should I delete this from within my class destructor?
Allocating memory in constructors
Is it okay to use new inside a constructor to allocate memory for my class?
Identifying Memory Leaks
How can I tell if my C++ program has a memory leak?
Returning from multiple points
What if my function needs to return from multiple points? How can I ensure all allocated memory is freed?
Writing a memory manager
Can I write my own memory manager to replace new and delete?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant