C++ Memory Management
In this page:
What is Memory Management?
Memory management in C++ is the process of allocating space for data as a program needs it and releasing that space when it's no longer needed, done manually with new/delete or automatically through RAII-based smart pointers.
Example: What is Memory Management?
#include <iostream>
int main() {
int *ptr = new int(5);
std::cout << *ptr << std::endl;
delete ptr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Stack vs Heap Memory
C++ programs use two main regions of memory: the stack, which automatically manages local variables tied to function calls, and the heap, a pool of memory that must be explicitly allocated and freed (or managed by a smart pointer).
Example: Stack vs Heap Memory
#include <iostream>
int main() {
int stackVar = 10;
int *heapVar = new int(20);
std::cout << stackVar << " " << *heapVar << std::endl;
delete heapVar;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Static vs Dynamic Allocation
Static allocation, like a regular array declaration, fixes memory size at compile time, while dynamic allocation, using new, lets a program decide how much memory it needs while it's actually running.
Example: Static vs Dynamic Allocation
#include <iostream>
int main() {
int staticArr[3] = {1, 2, 3};
int size = 3;
int *dynamicArr = new int[size];
dynamicArr[0] = 5;
std::cout << staticArr[0] << " " << dynamicArr[0] << std::endl;
delete[] dynamicArr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Allocate-Use-Free Lifecycle
Every block of dynamically allocated memory follows a lifecycle: it's allocated with new, used through a pointer, and then released exactly once with delete (or delete[] for arrays) when it's no longer needed.
Example: The Allocate-Use-Free Lifecycle
#include <iostream>
int main() {
int *ptr = new int(5);
std::cout << *ptr << std::endl;
delete ptr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Modern C++ Prefers Smart Pointers
Modern C++ encourages using smart pointers like unique_ptr and shared_ptr instead of raw new/delete, since they automatically release their memory when they go out of scope, preventing leaks and use-after-free bugs.
Example: Modern C++ Prefers Smart Pointers
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(42);
std::cout << *ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: