The Analogy: Renting Storage Instead of Using Your Own Cupboard
Every variable you have declared so far lives in a cupboard in your own house. You say int x; and the space appears; the moment the function ends, the cupboard is emptied for you. It is free, it is instant, and it is completely automatic — that is the stack.
The catch is that your house is small and its rooms are fixed. You must know at build time how big every cupboard is, and nothing can outlive the room it stands in.
Dynamic memory is renting a storage unit across town — the heap. You phone up and ask for as much space as you want, at any moment, in any size you decide while the program is running. The unit stays yours after you leave the room you rented it from; you can hand the key to someone else and they can still get in.
And that is the whole trade. Renting gives you three things the stack cannot: size decided at runtime, lifetime longer than the enclosing scope, and capacity far beyond the stack's few megabytes. In exchange you take on one obligation: you must hand the key back. Nobody tidies the unit for you. Forget, and you keep paying for space you can no longer even find — a memory leak. Hand the same key back twice, or use it after returning it, and the results are far worse than a leak.
Modern C++ has a firm answer to that obligation, which we build to at the end of this lesson: let an object own the key and return it in its destructor. But you cannot use smart pointers well without understanding what they are automating, so first we do it by hand.
Syntax or Core Structure
#include <iostream>
#include <string>
int main() {
// A single object
int* count = new int; // uninitialised -- contains garbage
int* score = new int(90); // initialised to 90
int* zero = new int{}; // value-initialised to 0
*score += 5;
std::cout << "score: " << *score << "\n"; // 95
delete count; // hand each key back exactly once
delete score;
delete zero;
// An array -- the size can come from anywhere, including the user
int n = 0;
std::cout << "how many? ";
std::cin >> n;
double* readings = new double[n]{}; // n doubles, all 0.0
for (int i = 0; i < n; ++i) {
readings[i] = i * 1.5; // index it like an array
}
double total = 0.0;
for (int i = 0; i < n; ++i) total += readings[i];
std::cout << "total: " << total << "\n";
delete[] readings; // NOTE the brackets -- array form
readings = nullptr; // no longer points anywhere valid
// An object
std::string* label = new std::string("dynamic");
std::cout << *label << " has " << label->size() << " chars\n";
delete label;
}
Three rules are visible in that code and worth stating flatly:
- Every
newneeds exactly onedelete. - Every
new[]needs exactly onedelete[]. Mixing the forms is undefined behaviour. - After deleting, set the pointer to
nullptrif it stays in scope.
Technical Depth: Stack, Heap, and Everything That Can Go Wrong
The two regions
void demo() {
int onStack = 5; // freed automatically when demo() returns
int* onHeap = new int(5); // stays until YOU delete it
delete onHeap;
}
| Stack | Heap | |
|---|---|---|
| Allocated by | Declaring a variable | new |
| Freed by | Leaving scope, automatically | delete, by you |
| Size known | At compile time | At runtime |
| Typical limit | 1–8 MB per thread | Available RAM |
| Speed | Extremely fast (move a pointer) | Slower (bookkeeping, may search) |
| Fragmentation | Impossible | Possible |
| Can outlive its scope | No | Yes |
The stack is faster and safer, so prefer it. Go to the heap only for one of the three reasons in the analogy: runtime size, longer lifetime, or sheer bulk.
Returning heap memory from a function
This is the classic legitimate use — and the reason new exists in the first place:
int* makeBuffer(int size) {
return new int[size]{}; // survives the return; caller must delete[]
}
int* broken() {
int local[10]{};
return local; // DANGLING -- local dies at the closing brace
}
But notice the cost of the working version: makeBuffer has handed the caller an obligation. Nothing in the signature says "you must delete[] this", and nothing enforces it.
The four classic bugs
1. Leak — forgot to delete.
void leak() {
int* p = new int(42);
// no delete -- 4 bytes lost for the life of the program
}
Called in a loop, this consumes memory until the process dies. Covered fully in the memory-leaks lesson.
2. Dangling pointer — used after delete.
int* p = new int(42);
delete p;
std::cout << *p; // UNDEFINED BEHAVIOUR -- may even "work"
*p = 7; // corrupting memory that is not yours
This is the dangerous one, because it often appears to work. The memory is still physically there until something else claims it, so the bug surfaces days later somewhere unrelated.
3. Double delete.
int* p = new int(42);
delete p;
delete p; // UNDEFINED BEHAVIOUR -- usually a crash
delete on a nullptr is explicitly safe and does nothing, which is why nulling after delete makes a double delete harmless:
delete p;
p = nullptr;
delete p; // safe no-op
4. Mismatched forms.
int* one = new int(5);
int* many = new int[5];
delete[] one; // WRONG
delete many; // WRONG -- frees the first element only
new[] records how many objects it made so delete[] can call every destructor. delete calls one. For an array of std::string, delete instead of delete[] leaks every string's internal buffer.
Two exits, one delete: why manual cleanup does not scale
void process(bool early) {
int* data = new int[100];
if (early) {
return; // LEAK -- never reaches the delete
}
if (data[0] < 0) {
throw std::runtime_error("bad data"); // LEAK -- exception skips it
}
delete[] data;
}
Every return, every break, every throw between the new and the delete is a leak waiting to happen. You cannot fix this by being careful, because a function's exit paths multiply as it grows and an exception can leave from any line. This is the argument for RAII, not a style preference.
new on failure, and nullptr
new does not return nullptr when it cannot allocate — it throws std::bad_alloc:
try {
int* huge = new int[1'000'000'000'000];
delete[] huge;
} catch (const std::bad_alloc& e) {
std::cout << "allocation failed: " << e.what() << "\n";
}
So if (!p) ... after a plain new is dead code inherited from C. The non-throwing form exists if you want it: new (std::nothrow) int[n] returns nullptr instead.
Initialisation is not automatic
int* a = new int; // GARBAGE
int* b = new int(); // 0
int* c = new int{}; // 0
int* d = new int(7); // 7
int* arr1 = new int[5]; // five pieces of garbage
int* arr2 = new int[5]{}; // five zeros
int* arr3 = new int[5]{1, 2}; // 1, 2, 0, 0, 0
Always use the brace form. Reading uninitialised memory is undefined behaviour, and the values are often plausible, which makes it hard to spot.
new/delete versus malloc/free
new / delete | malloc / free | |
|---|---|---|
| Calls constructors/destructors | Yes | No |
| Returns | Typed pointer | void*, needs a cast |
| Size | Computed for you | sizeof by hand |
| On failure | Throws std::bad_alloc | Returns nullptr |
| Can be overloaded | Yes | No |
Never mix them: memory from malloc must go to free, memory from new to delete. And for a class type, malloc gives you raw bytes with no object in them at all.
Where this is going
#include <memory>
std::unique_ptr<int> p = std::make_unique<int>(42);
std::unique_ptr<int[]> arr = std::make_unique<int[]>(100);
// no delete anywhere -- freed automatically, on every exit path, including throws
Or, for a run of values, simply std::vector<int> v(n); — which allocates on the heap for you and frees itself. In production C++, that is what you should write. Raw new and delete remain worth knowing because they explain what those tools do, and because you will read plenty of older code that uses them.
Real World Example: A Growable Sensor Log, Built by Hand
The point of this example is to write, once, the thing std::vector does for you — so that "a vector is an array that manages its own memory" stops being a slogan and becomes something you have seen the inside of. A logger reads samples from a sensor without knowing in advance how many will arrive, so its storage has to grow at runtime.
#include <iostream>
#include <iomanip>
#include <stdexcept>
class SensorLog {
public:
explicit SensorLog(std::size_t initialCapacity = 4)
: capacity(initialCapacity == 0 ? 1 : initialCapacity),
count(0),
samples(new double[capacity]{}) {} // acquire in the constructor
~SensorLog() {
delete[] samples; // release in the destructor
}
// Copying would duplicate the pointer and cause a double delete.
SensorLog(const SensorLog&) = delete;
SensorLog& operator=(const SensorLog&) = delete;
void add(double reading) {
if (count == capacity) {
grow();
}
samples[count] = reading;
++count;
}
double at(std::size_t index) const {
if (index >= count) {
throw std::out_of_range("SensorLog index out of range");
}
return samples[index];
}
std::size_t size() const { return count; }
std::size_t capacityNow() const { return capacity; }
double highest() const {
if (count == 0) throw std::out_of_range("empty log");
double best = samples[0];
for (std::size_t i = 1; i < count; ++i) {
if (samples[i] > best) best = samples[i];
}
return best;
}
double mean() const {
if (count == 0) return 0.0;
double total = 0.0;
for (std::size_t i = 0; i < count; ++i) total += samples[i];
return total / count;
}
private:
void grow() {
std::size_t newCapacity = capacity * 2;
double* bigger = new double[newCapacity]{}; // 1. get the new block
for (std::size_t i = 0; i < count; ++i) { // 2. move the contents
bigger[i] = samples[i];
}
delete[] samples; // 3. release the old block
samples = bigger; // 4. adopt the new one
capacity = newCapacity;
std::cout << " [grew to capacity " << capacity << "]\n";
}
std::size_t capacity;
std::size_t count;
double* samples;
};
void summarise(const SensorLog& log) {
std::cout << std::fixed << std::setprecision(2);
std::cout << "samples: " << log.size()
<< " (capacity " << log.capacityNow() << ")\n";
std::cout << "highest: " << log.highest() << "\n";
std::cout << "mean: " << log.mean() << "\n";
}
int main() {
SensorLog log(2); // deliberately small
const double readings[] = {21.5, 22.1, 23.8, 22.9, 24.4, 21.0, 25.2};
for (double r : readings) {
log.add(r);
}
summarise(log);
std::cout << "first: " << log.at(0) << "\n";
std::cout << "last: " << log.at(log.size() - 1) << "\n";
try {
log.at(99);
} catch (const std::out_of_range& e) {
std::cout << "caught: " << e.what() << "\n";
}
return 0; // destructor frees the block
}
Output:
[grew to capacity 4]
[grew to capacity 8]
samples: 7 (capacity 8)
highest: 25.20
mean: 23.01
first: 21.50
last: 25.20
caught: SensorLog index out of range
Work through what this class is actually doing. The constructor's initialiser list allocates the block and the destructor frees it — that pairing is the whole idea of RAII, and it is why there is no delete[] anywhere in main. Every exit path from main, including the thrown out_of_range, runs that destructor, which is precisely the problem the "two exits, one delete" section above could not solve with manual cleanup.
grow is the interesting part, and its four steps are in that order for a reason. You allocate the new block before freeing the old one, because you still need to read from the old one to copy the samples across. Reversing steps 2 and 3 would copy from freed memory. Doubling rather than adding one is what keeps add cheap on average: growing seven times from capacity 2 costs two reallocations, not five. And note the consequence — after grow, the old samples pointer is dangling. Anything that had been holding a pointer or reference into this log is now broken, which is exactly the vector-reallocation rule from the STL lesson, seen from the implementer's side.
The two = delete lines are not decoration. The implicitly generated copy constructor would copy the samples pointer, giving two SensorLog objects that believe they own the same block; both destructors would run and the second delete[] would be a double free. Any class holding a raw owning pointer must either delete its copy operations or implement them properly, and deleting them is the honest choice here. This is the rule of three, and it is why owning raw pointers is such a liability: a single class member drags four extra decisions in behind it.
Finally, at is bounds-checked and throws, while the internal loops in highest and mean index samples directly without checks — those indices are provably within count, so checking them would be cost for nothing. That is the same at()-versus-[] judgement the vector lesson made, applied here.
Now the punchline: the entire class is replaceable with three words.
std::vector<double> log;
log.push_back(21.5); // grows exactly the same way, no destructor needed
std::vector does the doubling, the copying, the freeing and the copy semantics correctly, with the exception safety handled. Write the vector. Write SensorLog once, as an exercise, so that you know what the vector is doing on your behalf — and then never write it again.
Common Mistakes
- Forgetting
delete. Everynewneeds one. In a loop, a small leak becomes a large one fast. deleteinstead ofdelete[]. Only the first element's destructor runs; the rest of the array leaks.- Using a pointer after deleting it. Undefined behaviour that frequently appears to work, then corrupts something else later.
- Deleting twice. Usually a crash. Set the pointer to
nullptrafter deleting to make a repeat harmless. - Leaking on an early
returnor athrow. Thedeleteat the bottom of the function is never reached. Use RAII. - Assuming
newreturnsnullptron failure. It throwsstd::bad_alloc. - Leaving memory uninitialised.
new int[n]is garbage;new int[n]{}is zeros. - Copying a class that owns a raw pointer. The default copy duplicates the pointer, not the memory, and you get a double free.
- Mixing
newwithfree, ormallocwithdelete. Undefined behaviour, and constructors or destructors get skipped. - Using the heap out of habit.
new int(5)whereint x = 5;would do is slower, riskier and longer.
Best Practices
- Prefer the stack. Use the heap only for runtime-decided size, a lifetime beyond the current scope, or genuinely large data.
- Prefer
std::vectorandstd::stringtonew[]. They are dynamic memory with the bookkeeping already correct. - Prefer
std::make_unique/std::make_sharedto rawnewwhen you truly need a single heap object. - If you must use
new, put it in a destructor's care immediately — one owner, one class, onedelete. - Match the forms.
newwithdelete,new[]withdelete[]. - Always brace-initialise:
new T{},new T[n]{}. - Null the pointer after deleting if it remains in scope.
- Never return a raw owning pointer from a function without documenting who frees it — better, return a
unique_ptror a container. - Delete or implement copy operations on any class holding an owning raw pointer.
- Run a leak checker. Valgrind, AddressSanitizer (
-fsanitize=address) or Dr. Memory find these bugs in seconds.
Practice Exercises
- Ask the user for a count
n, allocatenints withnew[], fill them with the firstnsquares, print them, anddelete[]them. Then rewrite it withstd::vector<int>and compare the line counts. - Write a function
int* duplicate(const int* source, std::size_t n)that heap-allocates a copy of an array and returns it. Document who is responsible for freeing it, then call it and free it correctly. - Write a class
Bufferthat allocatescharstorage in its constructor and frees it in its destructor. Print a message in each so you can watch the pairing. Then add= deletefor the copy constructor and explain, in a comment, what would go wrong without it. - Take the "two exits, one delete"
processfunction from this lesson and fix the leaks two ways: once by addingdelete[]on every path, and once by replacing the raw array with astd::vector. Explain which version you would rather maintain and why.