Memory Management (C++)
Memory management in C++ is how a program allocates and releases memory. Unlike garbage-collected languages, C++ gives you direct control, dividing memory between the stack and the heap.
C++
Stack memory is automatic: local variables are created and destroyed as functions enter and exit. Heap memory is manual: you request it with new (or via containers and smart pointers) and must ensure it is freed.
Because there is no garbage collector, mismanaging memory causes leaks or crashes. The modern approach is to rely on RAII, smart pointers, and standard containers so cleanup happens automatically.
Examples
C++
#include <iostream>
#include <vector>
int main() {
int onStack = 5; // stack: freed automatically
std::vector<int> v = {1, 2}; // heap, but managed for you
std::cout << onStack << " " << v.size() << std::endl;
return 0;
}Output:
5 2