Dynamic Memory
Overview
Up until now, every variable you've created was stored on the Stack. Stack memory is incredibly fast, but strictly limited (usually ~1MB total), and variables are automatically destroyed the moment their function ends. If you need to spawn a massive 500MB Game Level, it will crash the Stack.
C++ allows you to request memory from the Heap—a massive pool of RAM (measured in Gigabytes). This is called 'Dynamic Allocation'. You use the new keyword to carve out memory at runtime, and the OS hands you a Pointer to that memory. However, Heap memory is NEVER destroyed automatically. You MUST manually destroy it using delete, or your program will leak memory until the computer crashes.
Syntax
// 1. ALLOCATING MEMORY (The Heap)
// We request 4 bytes for an integer from the OS.
// The OS gives us the address, which we store in 'ptr'.
int* ptr = new int;
// 2. USING THE MEMORY
*ptr = 999;
std::cout << "Heap Value: " << *ptr << "\n";
// 3. FREEING THE MEMORY (CRITICAL!)
// We give the memory back to the OS.
delete ptr;
// 4. NULLIFYING THE POINTER
// The pointer still holds the old address!
// We must wipe it to prevent 'Dangling Pointers'.
ptr = nullptr;Common Pitfalls
- The Memory Leak. If you allocate memory with
new, but the function ends before you calldelete, the pointer is destroyed, but the Heap memory is NOT. That memory is permanently locked and unusable until the program restarts. Do this in a loop, and your RAM usage will hit 100% in seconds. - The Dangling Pointer. Calling
delete ptr;destroys the data, butptrstill physically holds the memory address. If you try to dereference it again (*ptr = 5;), you are writing data to unowned RAM, which will violently crash the app.
Interview Questions
The Stack is small, heavily optimized, and fully automatic; variables push and pop predictably as functions open and close. The Heap is massive, slightly slower, and completely manual; developers use new and delete to control exactly when data is born and dies, allowing data to persist long after the function that created it has ended.
Real-World Example
Returning a pointer from a function. If this was on the Stack, the variable would die when the function ended. By using the Heap, the data survives!
#include <iostream>
// Factory function generating data on the Heap
int* createEnemy() {
// Survives the function ending!
int* enemyHP = new int(100);
return enemyHP;
}
int main() {
int* boss = createEnemy();
std::cout << "Boss HP: " << *boss << "\n";
// The main function takes responsibility for cleaning it up!
delete boss;
boss = nullptr;
return 0;
}Check Your Knowledge
Test your understanding of Dynamic Memory with these quick questions.