Notes
All notes

Memory Management (C++ Core #3)

C++ gives you three places to put an object — the stack, static storage, and the heap — and one rule that keeps them straight: every allocation needs exactly one owner responsible for releasing it. Everything in this post is a consequence of that rule.

Stack, heap, and static storage

A running process has a few regions:

Region Holds Lifetime Cost
stack locals, parameters, return addresses until the function returns one pointer bump
heap new/malloc objects until released allocator search, syscalls, fragmentation
static / data globals, static locals whole program fixed at load
code / text machine instructions whole program read-only
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  r/.style={draw, thick, minimum width=3.0cm, minimum height=0.62cm, font=\scriptsize}]
  \node[r, fill=gray!8] (t) at (0,2.6) {code / text};
  \node[r, fill=blue!12] (d) at (0,1.9) {data + bss (globals)};
  \node[r, fill=orange!15] (h) at (0,1.2) {heap $\longrightarrow$};
  \node[r, fill=green!15] (s) at (0,0.5) {$\longleftarrow$ stack};
  \draw[->, thick] (1.75,1.2) -- (2.3,1.2);
  \draw[->, thick] (1.75,0.5) -- (2.3,0.5);
  \node[font=\scriptsize, anchor=west] at (2.4,1.2) {grows up};
  \node[font=\scriptsize, anchor=west] at (2.4,0.5) {grows down};
  \node[font=\scriptsize, anchor=north] at (0,-0.1) {the two meet in the middle when memory runs out};
\end{tikzpicture}

Stack allocation is fast because it is just moving the stack pointer. Heap allocation is slower because the allocator must find a free block, and it may call into the kernel. A stack frame is usually limited to 1–8 MB, so a large local array can crash the program before it does anything.

void f() {
    int a[1'000'000];      // 4 MB on the stack: may overflow
    std::vector<int> v(1'000'000);   // heap, safe
}

Static storage is zero-initialized before main (for objects with static storage duration), then constant-initialized, then dynamically initialized in an unspecified order across translation units.

QQuestionWhy is int a[10'000'000]; inside a function a bad idea even though

it compiles?

ASolution

It needs 40 MB of stack, which is far beyond the usual 1–8 MB limit. The program crashes or the OS kills it. Use a heap container instead.

new and delete

A new expression does two things: allocate raw memory, then construct an object in it. delete does the reverse: run the destructor, then release the memory.

int* p = new int(42);        // allocate + initialize
delete p;                    // destroy + free

int* arr = new int[5]{1,2,3,4,5};   // array new
delete[] arr;                        // array delete

Mismatching the forms is UB:

int* p = new int[10];
delete p;          // UB: should be delete[]

The compiler cannot catch it, because both pointers have the same type. This is why raw arrays should be std::vector.

new throws std::bad_alloc on failure unless you use the nothrow form:

int* p = new (std::nothrow) int[1000];
if (!p) { /* handle */ }

new returns a typed pointer and runs constructors, so it is not the same as malloc. For a class type, new T calls T::T(), and delete p calls ~T().

QQuestionWhat happens if a constructor throws during new?
ASolution

The memory allocated for the object is released automatically and the exception propagates. That is why new failing with an exception does not leak the allocation.

malloc, calloc, realloc, free

The C allocation API works in bytes and knows nothing about constructors.

int* p = (int*)malloc(10 * sizeof(int));    // uninitialized
int* q = (int*)calloc(10, sizeof(int));     // zeroed
p = (int*)realloc(p, 20 * sizeof(int));     // resize, may move
free(p);
free(q);

Never mix families:

int* p = new int(5);
free(p);            // UB: new with free
int* q = (int*)malloc(sizeof(int));
delete q;           // UB: malloc with delete
QQuestionWhy does realloc need a temporary pointer?
ASolution

On failure it returns NULL without freeing the original block. p = realloc(p, n) overwrites the only pointer to the original block, leaking it.

Memory leaks, use-after-free, double free, overflow

Four bugs cover most memory questions.

Memory leak — allocated, never released. The program keeps running and the memory is unreachable.

void leak() {
    int* p = new int[100];
    if (error) return;      // p is lost
    delete[] p;
}

Use-after-free — the pointer is used after delete. Reading is UB, writing is UB, and the allocator may have reused the block for something else.

int* p = new int(1);
delete p;
std::cout << *p;    // UB

Double free — releasing the same block twice corrupts the allocator’s metadata. delete on an already-deleted pointer is UB; delete on nullptr is fine, which is why “set to null after delete” is a common (if incomplete) habit.

int* p = new int(1);
delete p;
delete p;           // UB

Buffer overflow — writing past the end of an allocation.

int* a = new int[4];
a[4] = 1;           // out of bounds, UB
delete[] a;

None of these are caught by the type system. They are caught by tools:

g++ -fsanitize=address,undefined -g main.cpp   # ASan + UBSan
valgrind ./a.out

AddressSanitizer places red zones around allocations and reports the exact line of an overflow or a use-after-free. It is the single most useful flag when debugging memory questions.

QQuestionWhy is delete p; p = nullptr; not a complete fix for double free?
ASolution

It only fixes the copy of p you null out. Other pointers or references to the same block still dangle, and deleting through one of them is still UB.

Alignment, padding, and over-aligned types

Every type has an alignment: the address of an object must be a multiple of it. int usually needs 4, double 8, a pointer 8, and a class takes the strictest alignment of its members.

alignof(int);        // 4
alignof(double);     // 8
alignof(char);       // 1

struct S { char c; int i; };
sizeof(S);           // 8, not 5: 3 bytes of padding
alignof(S);          // 4

The compiler inserts padding so each member is correctly aligned. That is why member order changes the size (Ch. 8).

malloc and new return memory aligned for any fundamental type (alignof(std::max_align_t), usually 16). Over-aligned types need alignas and aligned allocation:

struct alignas(32) Vec { float x[8]; };
Vec* v = new Vec;          // C++17 new respects alignas

Before C++17, new did not guarantee over-alignment for types with extended alignment, which is why posix_memalign and _aligned_malloc exist.

QQuestionDoes sizeof(S) in the example above equal sizeof(char) + sizeof(int)?
ASolution

No. It is 8 because 3 padding bytes sit after c so that i starts at an address divisible by 4.

Ownership and RAII

Ownership answers “who is responsible for releasing this?”. If two parts of the code both think they own a heap object, you get a double free. If neither does, you get a leak.

RAII (Resource Acquisition Is Initialization) ties the resource to an object’s lifetime: acquire in the constructor, release in the destructor. Then scope exit — including exceptions — releases it automatically.

class Buffer {
    int* data;
    size_t n;
public:
    explicit Buffer(size_t n) : data(new int[n]), n(n) {}
    ~Buffer() { delete[] data; }                 // release
    Buffer(const Buffer&) = delete;              // no copies (Ch. 4)
    Buffer& operator=(const Buffer&) = delete;
    int& operator[](size_t i) { return data[i]; }
};

void f() {
    Buffer b(100);
    b[0] = 1;
    throw std::runtime_error("boom");   // destructor still runs
}

RAII is the reason std::vector, std::string, std::fstream, std::lock_guard, and the smart pointers exist. They all do the same thing for different resources.

QQuestionWhat happens to a std::vector’s heap buffer when an exception is

thrown after it is created?

ASolution

The vector’s destructor runs during stack unwinding and frees the buffer. That is RAII, and it is why manual new/delete in exception-throwing code leaks so easily.

Smart pointers

The standard library gives three ownership models.

std::unique_ptr<T> — exclusive ownership, move-only, zero overhead compared to a raw pointer.

#include <memory>

auto p = std::make_unique<int>(42);
std::cout << *p;              // 42
// std::unique_ptr<int> q = p;          // error: not copyable

std::unique_ptr<int> q = std::move(p);  // ownership transferred
// p is now null

Use it for every owning pointer. Custom deleters handle non-delete resources:

auto file = std::unique_ptr<FILE, decltype(&fclose)>(fopen("a.txt", "r"), &fclose);
auto arr  = std::make_unique<int[]>(10);        // array form

std::shared_ptr<T> — shared ownership through a control block holding a strong count and a weak count. The object is destroyed when the strong count hits zero.

auto a = std::make_shared<int>(7);   // one allocation for object + control block
std::shared_ptr<int> b = a;          // strong count 2
std::cout << a.use_count();          // 2
b.reset();                           // count 1

make_shared is preferred over shared_ptr<T>(new T) because it allocates the object and the control block together.

std::weak_ptr<T> — a non-owning observer. It does not change the strong count, and you must lock() it to get a shared_ptr (or an empty one if the object is gone).

std::weak_ptr<int> w = a;
if (auto s = w.lock()) {
    std::cout << *s;        // object still alive
} else {
    // expired
}

weak_ptr exists to break cycles. With shared_ptr on both sides of a parent- child link, each keeps the other’s count at 1 forever.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.5cm, minimum height=0.6cm, font=\scriptsize, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!12] (s1) at (0,0) {shared\_ptr A};
  \node[b, fill=blue!12] (s2) at (3.2,0) {shared\_ptr B};
  \node[b, fill=orange!18] (c) at (1.6,-1.2) {control block\\strong = 2};
  \node[b, fill=green!18] (o) at (1.6,1.15) {object};
  \draw[a] (s1) -- (c); \draw[a] (s2) -- (c);
  \draw[a] (c) -- (o);
  \node[font=\scriptsize, anchor=west] at (4.1,-1.2) {when strong hits 0, object dies};
\end{tikzpicture}
Pointer Ownership Copy Cost
unique_ptr exclusive no (move only) same as raw
shared_ptr shared yes, atomic-ish count control block + indirection
weak_ptr none yes needs lock() to use
QQuestionWhy does a shared_ptr cycle leak even though both pointers are

“smart”?

ASolution

Each object holds a strong reference to the other, so neither strong count ever reaches zero. One side of the cycle must be a weak_ptr.

Bugs and edge cases

QQuestionYou need a factory that returns a Derived as a Base. What should

the return type be, and what must Base have?

ASolution

std::unique_ptr<Base> (or shared_ptr<Base>), and Base must have a virtual destructor, or deleting through the base pointer is UB.

Next: Object-Oriented Programming (C++ Core #4) — copy versus move, vtables, and the dispatch rules.