C++ Memory Management
Local variables live on the stack: they are created when their block starts and destroyed automatically when it ends. Sometimes that is not enough — you may need memory whose size is only known at runtime, or an object that outlives the function that created it. For that, C++ lets you allocate memory on the heap (also called the free store) with new and release it with delete.
Stack vs heap
| Stack | Heap | |
|---|---|---|
| Allocated by | declaring a variable | new (or a container / smart pointer) |
| Freed by | the end of the scope, automatically | delete — or automatically by an owner object |
| Size | small (often 1–8 MB) | large (limited by system memory) |
| Speed | very fast | slower |
new and delete
new creates an object on the heap and returns a pointer to it. When you are done, delete destroys the object and gives the memory back:
#include <iostream>
using namespace std;
int main() {
int* counter = new int(5); // allocate one int, initialised to 5
*counter += 10;
cout << "Counter: " << *counter << "\n";
delete counter; // release it
counter = nullptr; // avoid a dangling pointer
double* price = new double{}; // value-initialised to 0
cout << "Price: " << *price << "\n";
delete price;
}Counter: 15
Price: 0
Dynamic arrays: new[] and delete[]
For an array whose size is decided at runtime, use new T[n] — and release it with the matching delete[]:
#include <iostream>
using namespace std;
int main() {
int n = 6; // imagine this came from user input
int* squares = new int[n];
for (int i = 0; i < n; i++) {
squares[i] = i * i;
}
for (int i = 0; i < n; i++) {
cout << squares[i] << " ";
}
cout << "\n";
delete[] squares; // [] because it was allocated with new[]
}0 1 4 9 16 25
Warning: Mixing them up (
deleteon memory fromnew[], or vice-versa) is undefined behaviour.
Objects on the heap
When you new a struct or class object, its constructor runs; delete runs its destructor. A small struct that announces itself shows the lifetime clearly:
#include <iostream>
#include <string>
using namespace std;
struct Resource {
string name;
Resource(string n) : name(n) { cout << "acquire " << name << "\n"; }
~Resource() { cout << "release " << name << "\n"; }
};
int main() {
Resource onStack("stack-res");
Resource* onHeap = new Resource("heap-res");
cout << "working with " << onHeap->name << "\n";
delete onHeap;
cout << "end of main\n";
}acquire stack-res
acquire heap-res
working with heap-res
release heap-res
end of main
release stack-res
The stack object is cleaned up automatically at the closing brace of main; the heap object lives exactly until delete.
What can go wrong
Manual memory management is error-prone. These are the classic bugs:
| Bug | What happens |
|---|---|
Memory leak — forgetting delete |
the memory is never returned; long-running programs grow and grow |
Dangling pointer — using memory after delete |
undefined behaviour: garbage values or crashes |
| Double delete — deleting the same pointer twice | undefined behaviour, often a crash |
Mismatched delete — delete vs delete[] |
undefined behaviour |
int* p = new int(42);
delete p;
cout << *p; // BUG: dangling pointer (use after free)
delete p; // BUG: double deleteTools such as AddressSanitizer (g++ -fsanitize=address) and Valgrind detect these mistakes at runtime.
The modern way: let objects own memory
Modern C++ code rarely calls new and delete directly. Instead, an object owns the memory and frees it in its destructor — an idiom called RAII (Resource Acquisition Is Initialization). The standard library already provides such owners:
#include <iostream>
#include <vector>
#include <memory>
using namespace std;
int main() {
int n = 5;
vector<int> values(n); // dynamic array that frees itself
for (int i = 0; i < n; i++) values[i] = (i + 1) * 10;
cout << values.back() << "\n";
auto score = make_unique<int>(99); // a single heap int with one owner
cout << *score << "\n";
} // both are released here automatically — no delete needed50
99
Tip: Rule of thumb: use
std::vectorinstead ofnew[], andstd::unique_ptr/std::make_uniqueinstead ofnew. You will study smart pointers in detail later in the course.
Test yourself
Memory allocated with new int[10] must be released with…
- delete
- delete[]
- free
- Nothing, it is automatic
What is a memory leak?
- Reading past the end of an array
- Heap memory that is never released
- Deleting memory twice
- A pointer set to nullptr
Which is the preferred modern replacement for a dynamic array created with new[]?
- malloc
- std::vector
- A global array
- std::string