Module 2 · Memory
2.5Dynamic memory and RAII
Allocate heap memory with new and free it with delete, see the three ways that goes wrong, and let RAII free it for you: the pattern behind std::vector and every modern C++ program.
On this page
- Key terms
- In 30 seconds
- new and delete
- Arrays: new[] and delete[]
- Three ways to get it wrong
- Forgetting to free: a memory leak
- Freeing twice: a double free
- Mixing up delete and delete[]
- RAII: let a destructor free it
- std::vector is RAII
- Which one should I use?
- Under the hood
- Common pitfalls
- Copying an object that owns a raw pointer
- Using memory after delete
- Try it yourself
Key terms
new- Creates an object on the heap and gives you a pointer to it:
new int(42). delete- Destroys an object made with
newand gives its memory back. Everynewneeds exactly onedelete. new[]anddelete[]- The array forms:
new float[n]makesnfloats on the heap, anddelete[] pfrees them. Each form must be paired with its own. - free (memory)
- To give heap memory back so it can be used again.
- memory leak
- Heap memory that is never freed. The program keeps it until it exits.
- LeakSanitizer
- A checker, included in
-fsanitize=addresson Linux, that lists every leak when the program exits. - double free
- Freeing the same memory twice. It's undefined behavior and can corrupt the heap.
- owner
- The one part of the program responsible for freeing a piece of memory or another resource.
- resource
- Anything you must give back after use: heap memory, an open file, a network connection, a lock.
- constructor
- A function with the same name as the struct that runs when an object is created.
- destructor (
~T()) - A function named
~plus the struct's name that runs automatically when an object is destroyed. - RAII
- Resource Acquisition Is Initialization: an object gets a resource in its constructor and gives it back in its destructor, so it's freed exactly once, automatically.
std::vector and std::string get memory from the heap and give it back without you doing anything. Underneath, they ask for memory and give it back the same way new and delete do. Doing that by hand is easy to get wrong: forget to free and memory leaks, free twice and the heap breaks. This lesson shows those mistakes, then RAII, the pattern that makes freeing automatic.
In 30 seconds
new T(…)creates an object on the heap and returns a pointer.delete pdestroys it. Arrays usenew T[n]anddelete[] p.- Every
newneeds exactly one matchingdelete, on every path through the code. Miss one and memory leaks; do it twice and it’s a double free. - RAII puts the
deletein a destructor. Destructors run automatically at the end of a scope, so the memory is freed exactly once. std::vector,std::stringand the smart pointers in the next lesson do this for you. Modern code almost never writesnewordelete.
new and delete
new int(42) asks the heap for room for one int, puts 42 there, and returns its address. You keep that address in a pointer. When you’re done, delete destroys the object and frees the memory.
#include <print>
int* count = new int(42);
*count += 1;
std::println("{}", *count);
delete count;Output
43
The pointer count lives on the stack and disappears at the end of its scope. The int on the heap doesn’t: it stays until something calls delete. After delete count, the pointer still holds the old address, but the memory there is no longer yours.
Arrays: new[] and delete[]
Use the heap when you only learn how many values you need while the program runs. new float[n] makes n floats side by side; the {} sets them all to 0. Free them with delete[], with square brackets.
#include <cstddef>
#include <print>
std::size_t n = 4;
float* pixels = new float[n]{};
pixels[3] = 0.75f;
std::println("{} {}", pixels[0], pixels[3]);
delete[] pixels;Output
0 0.75
Three ways to get it wrong
The compiler doesn’t track who should free what. That’s your job, and it goes wrong in three ways. Each one is undefined behavior or a slow waste of memory, and the sanitizers catch all three.
Forgetting to free: a memory leak
The usual leak isn’t a forgotten delete. It’s a delete that some path through the function skips, like an early return:
#include <cstddef>
#include <print>
bool normalize(std::size_t count) {
float* buffer = new float[count]{};
if (count > 3) {
std::println("too many values: {}", count);
return false; // returns before delete[]: the buffer leaks
}
std::println("normalized {} values", count);
delete[] buffer;
return true;
}
int main() {
normalize(2);
normalize(5);
}This fails when it runs
ERROR: LeakSanitizer: detected memory leaks
Direct leak of 20 byte(s) in 1 object(s) allocated from:
#0 operator new[](unsigned long)
#1 normalize(unsigned long) main.cpp:5
#2 main main.cpp:17
SUMMARY: AddressSanitizer: 20 byte(s) leaked in 1 allocation(s).The program prints both lines and reaches the end of main. Then LeakSanitizer lists the memory that was never freed: 20 bytes, the five 4-byte floats. A leak doesn’t crash anything. But a program that leaks a little on every request, or on every image it reads, slowly uses up all the memory it has.
Freeing twice: a double free
Two pointers can hold the same address. Delete through both, and the same memory is freed twice:
int* first = new int(7);
int* second = first; // both point at the same int
delete first;
delete second;This fails when it runs
ERROR: AddressSanitizer: attempting double-free on 0x… in thread T0:
#0 operator delete(void*, unsigned long)
#1 main main.cpp:4
0x… is located 0 bytes inside of 4-byte region [0x…,0x…)
freed by thread T0 here:
#0 operator delete(void*, unsigned long)
#1 main main.cpp:3
previously allocated by thread T0 here:
#0 operator new(unsigned long)
#1 main main.cpp:1
SUMMARY: AddressSanitizer: double-free main.cpp:4 in mainA double free can corrupt the heap’s own records, and the program fails later, somewhere unrelated. The fix is to decide which pointer is the owner, the one that frees, and treat every other pointer as a way to use the object, never to free it.
Mixing up delete and delete[]
Memory from new[] must be freed with delete[], and memory from new with delete. When both are in the same function, GCC and Clang see the mismatch, and with warnings as errors it doesn’t compile:
float* pixels = new float[4]{};
delete pixels;The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:2:8: error: ‘void operator delete(void*, long unsigned int)’ called on pointer returned from a mismatched allocation function [-Werror=mismatched-new-delete]
2 | delete pixels;
| ^~~~~~
main.cpp:1:30: note: returned from ‘void* operator new [](long unsigned int)’
1 | float* pixels = new float[4]{};
| ^
cc1plus: all warnings being treated as errorsWhen the delete is in another function, the compiler can’t see where the pointer came from. AddressSanitizer catches it when the program runs:
void release(float* pixels) {
delete pixels; // should be delete[]
}
int main() {
float* pixels = new float[4]{};
release(pixels);
}This fails when it runs
ERROR: AddressSanitizer: alloc-dealloc-mismatch (operator new [] vs operator delete) on 0x…
#0 operator delete(void*, unsigned long)
#1 release(float*) main.cpp:2
#2 main main.cpp:7
0x… is located 0 bytes inside of 16-byte region [0x…,0x…)
allocated by thread T0 here:
#0 operator new[](unsigned long)
#1 main main.cpp:6
SUMMARY: AddressSanitizer: alloc-dealloc-mismatch main.cpp:2 in release(float*)
HINT: if you don't care about these errors you may set ASAN_OPTIONS=alloc_dealloc_mismatch=0Undefined behaviorThese bugs often look fine without sanitizers
A leak, a double free or a mismatched delete may do nothing visible in a small test and crash in a big run. Build with -fsanitize=address,undefined while you develop; Setting up shows how.
RAII: let a destructor free it
Every one of those bugs comes from the same place: a person has to remember to call delete, once, on every path. C++ already has something that runs exactly once, on every path: a destructor, which you met in Stack, heap and lifetime. A struct can have two special functions:
- A constructor, named after the struct, runs when an object is created. Here it gets the memory. The part after
:sets the members before the body runs. - A destructor, named
~plus the struct’s name, runs when the object is destroyed: at the closing brace of its scope, or when a function returns early.
#include <cstddef>
#include <print>
struct Buffer {
float* data;
std::size_t size;
Buffer(std::size_t n) : data(new float[n]{}), size(n) {
std::println("allocated {} floats", size);
}
~Buffer() {
delete[] data;
std::println("freed {} floats", size);
}
};
int main() {
std::println("start");
{
Buffer image(4);
Buffer mask(2);
image.data[0] = 0.5f;
std::println("working: {}", image.data[0]);
}
std::println("end");
}Output
start allocated 4 floats allocated 2 floats working: 0.5 freed 2 floats freed 4 floats end
At the closing brace, both buffers are destroyed, in the reverse of the order they were made, and each destructor frees its own memory. Nobody calls delete by hand. This pattern is called RAII, Resource Acquisition Is Initialization: getting a resource is tied to creating an object, and giving it back is tied to destroying it.
Key ideaThe destructor runs on every way out
Whether the scope ends at its closing brace, through a return or a break, or because an exception jumps out of it on its way to a catch (Module 5), the destructors of the objects in that scope run. That’s what makes RAII reliable.
std::vector is RAII
You rarely need to write a class like Buffer, because the standard library already has one. std::vector<float> gets its memory in its constructor and frees it in its destructor. Here is the leaking normalize from above, fixed by using a vector:
#include <cstddef>
#include <print>
#include <vector>
bool normalize(std::size_t count) {
std::vector<float> buffer(count); // count floats, all 0
if (count > 3) {
std::println("too many values: {}", count);
return false; // buffer's destructor frees the memory here
}
std::println("normalized {} values", buffer.size());
return true;
}
int main() {
normalize(2);
normalize(5);
}Output
normalized 2 values too many values: 5
No delete, no leak, and no way to forget one later when someone adds another return. std::string works the same way, and so do files, locks and the smart pointers in the next lesson.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
std::vector, std::string | You need a run of values or some text whose size you learn at run time. | They free their memory themselves, and they also grow and copy correctly. | std::vector<float> buffer(n); |
std::unique_ptr | You need one object on the heap, with one owner. | It deletes the object when the owner goes away. The next lesson covers it. | auto model = std::make_unique<Model>(); |
| Your own RAII class | You hold a resource the standard library has no type for, like a handle from a C library. | The release is written once, in the destructor, and runs on every path. | Constructor gets it, destructor gives it back. |
new and delete | Almost never: only inside the code of an RAII class. | Every path must free exactly once, with the right form, and nothing checks it for you. | delete only in a destructor. |
Rule of thumb: don’t write delete outside a destructor, and prefer not to write new at all: use a container or a smart pointer.
Under the hood
new does two things: it asks the heap for enough bytes, then runs the constructor in them. delete does the reverse: it runs the destructor, then hands the bytes back. new[] and delete[] do the same for every element, which is why each needs its partner: for types with destructors, new[] usually stores the element count just before the elements, and only delete[] knows to look for it.
A Buffer object itself is small. On the stack, image is 16 bytes on this platform, a pointer and a size, whatever the number of floats. The floats are on the heap:
std::vector looks much the same inside, as Stack, heap and lifetime showed: a pointer to its heap block plus a little bookkeeping, and a destructor that frees the block.
Modern C++Why modern code rarely writes new
Every new creates a promise: exactly one delete, of the right form, on every path the program can take, including ones added next year. The compiler can’t check that promise. RAII types keep it in one place, tested once, so code that uses std::vector, std::string and smart pointers doesn’t have to keep it at all.
Common pitfalls
Copying an object that owns a raw pointer
Copying a Buffer copies its members, and that includes the pointer. Now two objects hold the same address, and both destructors free it:
#include <cstddef>
struct Buffer {
float* data;
std::size_t size;
Buffer(std::size_t n) : data(new float[n]{}), size(n) {}
~Buffer() { delete[] data; }
};
int main() {
Buffer image(4);
Buffer copy = image; // copies the pointer, not the floats
}This fails when it runs
ERROR: AddressSanitizer: attempting double-free on 0x… in thread T0:
#0 operator delete[](void*)
#1 Buffer::~Buffer() main.cpp:8
#2 main main.cpp:14
0x… is located 0 bytes inside of 16-byte region [0x…,0x…)
freed by thread T0 here:
#0 operator delete[](void*)
#1 Buffer::~Buffer() main.cpp:8
#2 main main.cpp:14
previously allocated by thread T0 here:
#0 operator new[](unsigned long)
#1 Buffer::Buffer(unsigned long) main.cpp:7
#2 main main.cpp:12
SUMMARY: AddressSanitizer: double-free main.cpp:8 in Buffer::~Buffer()The simplest fix is to not own a raw pointer at all: make the member a std::vector<float>. Then copying a Buffer copies the floats, each copy frees its own, and you don’t need a destructor. Module 4 shows how to control copying for classes that really must own a raw resource.
Using memory after delete
After delete p, p still holds the old address, and reading through it is undefined behavior (AddressSanitizer reports heap-use-after-free). If a pointer lives on after its delete, set it to nullptr so the mistake is easy to spot. delete on a nullptr does nothing, so that also makes a second delete through the same pointer harmless. Better still, let an RAII type own the memory, so there’s no pointer left over.
Try it yourself
Try it yourself
average_of_first fills a heap buffer with readings and averages them. It works for 4 readings, but it leaks when count is more than 8, because the early return skips delete[]. Make it leak-free by replacing new[] and delete[] with a std::vector<float>, then call it with 10 as well.
#include <cstddef>
#include <print>
float average_of_first(std::size_t count) {
float* readings = new float[count]{};
if (count > 8) {
return -1.0f; // too many readings
}
float total = 0.0f;
for (std::size_t i = 0; i < count; ++i) {
readings[i] = 1.5f * static_cast<float>(i);
total += readings[i];
}
delete[] readings;
return total / static_cast<float>(count);
}
int main() {
std::println("{}", average_of_first(4));
}Expected output
2.25 -1
Show a hint
Replace float* readings = new float[count]{}; with std::vector<float> readings(count); and remove the delete[] line. Indexing with [] works the same on a vector.
Show a solution
#include <cstddef>
#include <print>
#include <vector>
float average_of_first(std::size_t count) {
std::vector<float> readings(count);
if (count > 8) {
return -1.0f; // too many readings
}
float total = 0.0f;
for (std::size_t i = 0; i < count; ++i) {
readings[i] = 1.5f * static_cast<float>(i);
total += readings[i];
}
return total / static_cast<float>(count);
}
int main() {
std::println("{} {}", average_of_first(4), average_of_first(10));
}std::vector<float> readings(count) makes count floats set to 0, and its destructor frees them at every return. The early return for more than 8 readings no longer leaks, and there's no delete[] to forget.
Saved in this browser only.