Skip to content
BIASED

Dynamic memory allocation and strings

Stack vs heap, the malloc/free contract, utilization and fragmentation, brk/mmap, classic bugs and C strings.

Stack and heap

After load the image is almost fixed. Data whose size and lifetime are known only at run time needs the heap. Static storage lives in .data/.bss; automatic in a stack frame; allocated from malloc until free. Returning a pointer to a local array is wrong: the frame is gone. In the note’s example the main-thread stack is 8176 KiB.

Internal fragmentation is waste inside blocks; external fragmentation is free memory in pieces too small to use. In the worked example 80 free bytes could not serve a 72-byte block.

free(p) receives only an address. The allocator therefore stores the block’s size just before the payload, in a header. Because every block size is a multiple of 8, the three lowest bits of the size are always zero, and the lowest one can record whether the block is allocated: a header value of 25 means a 24-byte block in use, 24 a 24-byte free block (Bryant and O’Hallaron, 2016, §9.9.6). In the allocator of this note the header is 4 bytes and the block size counts the header too.

The malloc/free contract

malloc / calloc / realloc / free in <stdlib.h>. Bytes are uninitialized (except calloc); alignment is usually 16 on 64-bit; realloc may move. Peak utilization Uk=max⁡iPi/HkU_k=\max_i P_i/H_k.

For example, with free blocks of 48, 16 and 32 bytes in address order and a request that needs a 16-byte block, first fit splits the 48-byte block into 16 and 32 and leaves free blocks of 32, 16 and 32 bytes; best fit takes the 16-byte block exactly and leaves the 48 and 32 untouched, so a later request for a 40-byte block can still be served. Measurements on eight real C and C++ programs found near-zero fragmentation for several conventional policies, best fit and first fit in address order among them, once headers and alignment were accounted for (Johnstone and Wilson, 1998): a good policy is easy to find, and an efficient implementation of it is the hard part.

An in-heap allocator

A bump allocator only advances a pointer — a fast baseline without arbitrary free. A real allocator keeps metadata in the heap, a free list, and coalesces neighbors. External fragmentation: enough free bytes in total, but no single block large enough.

Segregated free lists keep one list per size class (for example 16, 32, 48 and 64 bytes, then powers of two). A request goes straight to the list of its class, which approximates best fit without searching the whole heap. Production allocators such as glibc’s, jemalloc and mimalloc are built on size classes, plus per-thread caches so that threads do not contend for one lock. The operating-system kernel uses the same idea in the slab allocator, which keeps caches of identical kernel objects, such as process descriptors, ready to hand out (Bonwick, 1994).

Where the heap comes from: brk and mmap

Pages arrive via brk/sbrk or mmap; small requests are served from a user-space reserve without a syscall every time.

The allocator of the worked example. It prints the block list after every request, each block as status, size and payload offset; compile and run with clang -std=c17 -Wall -Wextra -O0 alloc.c -o alloc && ./alloc:

Bugs and C strings

Leaks, use-after-free, double free, overflows. A C string ends at \0: "hi" occupies 3 bytes. Next the program must share the machine — Processes and threads. Stack vs heap. After load the image is almost fixed. Data whose size and lifetime are known only at run time need the heap. Static storage lives in .data/.bss; automatic in a stack frame; malloc until free. Returning a pointer to a local array is wrong: the frame is gone. In the notes’ example the main-thread stack is about 8176 KiB. Contract. malloc / calloc / realloc / free. Bytes uninitialized except calloc; alignment usually 16 on 64-bit; realloc may move. Peak utilization U_k=\max_i P_i/H_k compares live payload to heap size. Allocator guts. A bump pointer is the fast baseline without arbitrary free. Real allocators keep headers (size, flags), free lists, splitting and coalescing, often with boundary tags. External fragmentation: enough free bytes in total, no single block large enough. Pages arrive via brk/sbrk or mmap; small requests are carved in user space without a syscall every time; large requests may get a fresh mmap so free can munmap. Bugs & strings. Leaks, use-after-free, double free, overflows — AddressSanitizer catches many at test time. A C string ends at \\0: "hi" occupies 3 bytes; strcpy into a too-small buffer is undefined behaviour that still “works” until it corrupts the next header. Size classes and segregated free lists keep fragmentation down for common request sizes: a 16-byte request never walks a list of 4 KiB holes. Thread-local caches (tcmalloc, jemalloc) remove the central lock from the hot path at the cost of more retained memory per thread. For huge allocations, arenas backed by mmap let free return pages to the OS; shrinking with brk is harder because everything above the break must move. When debugging heap corruption, first check life cycle: who allocates, who frees, is the pointer still live?

Next: Processes and threads — sharing the machine once the heap works.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • malloc/free and block coalesceoptional

    On a free-list allocate, free and coalesce neighbors; check fragmentation.

    ~25 min · easier on a computer · The matching course topic has been read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.