Stack memory is fast but fixed in size. When your program needs to allocate memory whose size is only known at runtime (e.g., loading a 4K game texture or a 10,000-row database query), you must allocate memory dynamically on the Heap.
new and delete Operators#include <iostream>
int main() {
// 1. Allocate a single integer on the Heap
int* ptr = new int(250);
std::cout << "Heap value: " << *ptr << "\n";
delete ptr; // Deallocate heap memory
ptr = nullptr; // Prevent dangling pointer!
// 2. Allocate a dynamic array of integers on the Heap
int size = 5;
int* dynamicArr = new int[size]{10, 20, 30, 40, 50};
// CRITICAL: Always use delete[] for arrays!
delete[] dynamicArr;
dynamicArr = nullptr;
return 0;
}
A memory leak occurs when heap memory is allocated with new, but the pointer holding its address is lost or reassigned without calling delete. The memory remains occupied until the operating system shuts down the process. In servers running 24/7, memory leaks cause the system to crash with std::bad_alloc.
Boost your C++ proficiency by studying these closely connected core modules:
Modern automated heap management (unique_ptr).
Binding dynamic resources to deterministic scope destructors.
Handling std::bad_alloc during out-of-memory errors.