Dynamic storage allocation
Dynamic storage allocation in compilers: heap vs stack, allocation algorithms (first-fit, best-fit, worst-fit, buddy), fragmentation types, free-list management and basic garbage-collection methods (reference-counting, mark-and-sweep, copying).
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Compilers must manage memory for data whose size and lifetime are not known at compile time (the heap). Good dynamic storage allocation keeps programs correct, fast and memory‑efficient; poor allocation can cause fragmentation, slow allocation, or memory leaks. Engineers use these ideas when designing a language runtime, garbage collector, or memory allocator in the compiler backend or runtime library.
Key ideas
(Define terms before use and keep statements exact.)
Memory allocator — a runtime component that gives out and reclaims regions of memory on the heap on request (allocate and free). Use this term only for runtime modules that work during program execution.
Heap — the region of process memory used for dynamically allocated objects. Draw: a horizontal rectangle labelled “Heap”, with addresses increasing left→right or bottom→top; mark a free block and an allocated block inside.
Allocation request — a request that specifies a number of bytes to allocate. The allocator returns a pointer to a block at least that large.
Block — a contiguous region of heap memory that the allocator treats as one unit (either free or allocated). Each block often has a small header (and sometimes a footer) with metadata (size, status). Draw: a block as a rectangle with a small header at its left labelled "size/status" and a payload to the right.
Free list — a data structure of free blocks (often linked lists). A free block stores pointers to the next/previous free block in its payload area.
Internal fragmentation — wasted bytes inside an allocated block because the allocator gives a larger block than requested (for alignment or size-class reasons). Exact: internal_fragmentation = ∑(allocated_block_size - requested_size).
External fragmentation — free memory exists but is split into small, non‑contiguous pieces so it cannot satisfy a large request. A common exam metric: external_frag_fraction = 1 − (largest_free_block / total_free_memory). This measures how badly free memory is fragmented into smaller pieces.
First‑fit / Best‑fit / Worst‑fit — allocation search strategies over the free list.
- First‑fit: scan from the start of the free list and choose the first block big enough.
- Best‑fit: scan all free blocks and choose the smallest block >= request.
- Worst‑fit: choose the largest free block. State assumptions: these are simple strategies; their average behaviour depends on request patterns and free-list ordering.
Coalescing — when freeing a block, merge it with adjacent free blocks to reduce external fragmentation. Use boundary tags (a footer with size) so you can find the previous block whether allocated or free.
Segregated free lists / size‑classes — keep multiple free lists, one per block size range. This reduces search time and external fragmentation but may increase internal fragmentation due to rounding to size classes.
Buddy system — allocator that splits memory into blocks of size power-of-two. Exact rule: the system manages blocks in sizes
2^k · min_block_sizeand when a request arrives, choose smallest k with block_size ≥ request; if only a larger block exists, split recursively into two equal buddies until block_size fits; on free, if the buddy is free, coalesce back. Draw: a binary tree of splits with root = total region; leaves are current blocks. Assumption: min_block_size is given and total heap size is a power of two multiple of min_block_size.Garbage collection — automatic reclamation of memory that is no longer reachable. Two elementary algorithms often taught:
- Reference counting — every object has a reference count; increment when a pointer to it is stored, decrement when pointer removed; when count becomes zero, free immediately (and decrement counts of children). Limitation: cycles are not reclaimed.
- Mark‑and‑sweep — two phases: mark (from roots, traverse object graph and mark reachable objects), sweep (scan heap, free unmarked objects). Reclaims cyclic garbage (any unreachable objects).
Copying collector (Cheney) — divides heap into two semi-spaces; allocate in one space until full, then copy reachable objects to the other space during GC, compacting live data and leaving the from-space empty. This eliminates external fragmentation but needs extra memory for the other semi-space.
Generational collection — heuristic: most objects die young; split heap into generations and collect young generation more often with cheap copying. Assumption: empirical behaviour of typical programs. Requires a write barrier and a remembered set to track old-to-young pointers so minor (young) collections remain correct.
Performance tradeoffs — time cost of allocation/release vs memory efficiency vs simplicity. For example: first‑fit is fast on average but can fragment; best‑fit reduces wasted space at cost of slower search and may leave tiny fragments.
Formulas
allocated_block_size = round_up(requested_size + header_overhead, alignment) — allocated block size, where round_up(x,a) returns the smallest multiple of a ≥ x. Explain: sizes in bytes; alignment in bytes; applies to allocators with alignment constraints. If a footer is used, include footer_overhead in the sum.
internal_fragmentation = sum_over_allocated(allocated_block_size - requested_size) — bytes wasted inside allocated blocks; unit: bytes; applies after allocations complete or over time.
external_frag_fraction = 1 - (largest_free_block / total_free_memory) — dimensionless fraction between 0 and 1 when total_free_memory > 0; applies as a simple metric for external fragmentation (verify applicability in exams).
block_size = 2^k · min_block — buddy system block size; k ∈ Z≥0; units: bytes; applies in buddy allocators where sizes are powers of two.
Time-complexity notes (informal):
first-fit worst-case = O(n) — n = number of free blocks; worst-case when many small blocks checked.
best-fit worst-case = O(n) — must search all free blocks; typically slower than first-fit. worst-fit worst-case = O(n) — also scans the free list; can exacerbate fragmentation.
allocation in segregated lists ≈ O(1) — if exact size-class exists and no coalescing needed.
Worked examples
Example 1 — First‑fit allocation trace (university exam style): Given: heap initially one free block of 512 bytes, header_overhead=8 bytes, alignment=8 bytes. Sequence of requests: 100, 20, 200, free(20), 50. Show block sizes and fragmentation. Steps:
- Request 100. Required = 100 + 8 = 108 → rounded up to multiple of 8 → 112. Allocate first 112 from the 512 block. Remaining free block = 512 − 112 = 400.
- Request 20. Required = 20 + 8 = 28 → round up → 32. First free block 400 → allocate 32. Remaining free = 368.
- Request 200. Required = 200 + 8 = 208 → round up → 208. Free 368 → allocate 208. Remaining free = 160.
- free(20) → free the 32-byte block; now free blocks (in address order): [32], [160]. If allocator coalesces only with adjacent free blocks, and they are not adjacent, they remain separate.
- Request 50. Required = 50 + 8 = 58 → round up → 64. First‑fit scans and finds 32 (too small), then 160 (fits). Allocate 64 from 160 leaving 96. Results: allocated sizes = 112, 64, 208. Internal fragmentation = (112−100) + (64−50) + (208−200) = 12 + 14 + 8 = 34 bytes. Free blocks total = 32 + 96 = 128. External fragmentation metric: largest_free_block = 96, total_free = 128 → external_frag_fraction = 1 − (96/128) = 1 − 0.75 = 0.25.
Example 2 — Buddy system allocation (step trace): Given heap size = 256 bytes, min_block = 16 bytes. Request sequence: 70 bytes. Steps:
- Requested_size + header (assume 8) = 78 → next power-of-two block_size ≥ 78 is 128 (since 64 < 78 ≤ 128). Using formula block_size = 2^k · 16 → 128 = 8 · 16.
- Start with full 256 block. Split 256 → two 128 buddies. Use one 128 for this allocation; remaining blocks: one allocated 128, one free 128.
- Internal fragmentation = 128 − 78 = 50 bytes. Draw: show 256 block split; mark one 128 as allocated.
Example 3 — Mark‑and‑sweep trace (graph example): Heap objects: A(size=16) at addr1 → field points to B; B(size=24) at addr2 → points to C; C(size=12) at addr3 → points to nothing; D(size=20) at addr4 → unreachable. Root set = {A}. Steps: Mark phase: start at A → mark A, follow to B → mark B, follow to C → mark C. D is not visited. Sweep phase: scan all blocks: free any unmarked blocks. D is freed. Live objects A,B,C kept. After sweep, unmarked bits reset. Result: freed D; cycles would have been reclaimed by sweep because no need for reference counts.
Common mistakes
- In buddy examples, rounding to next power of two of (requested+overhead) rather than requested alone.
- Saying "best‑fit always minimizes fragmentation" — this is heuristic and not a provable guarantee for all sequences.
- For garbage collection, claiming reference counting reclaims cycles without qualification — cycles are a known limitation.
For your exam
Typical question types: definitions (internal/external fragmentation, buddy system, boundary tags), short notes (compare first‑fit/best‑fit; describe buddy allocator), derivations (calculate fragmentation or block layout for a sequence), algorithm traces (mark‑and‑sweep or copying collector), and small programs or pseudo-code to implement free-list coalescing or reference counting updates. What full‑marks answers include:
- Clear definitions of terms (bold if exam asks), with units where applicable.
- Correct rounding/alignment arithmetic and inclusion of header/footer sizes.
- Diagrams where asked: draw heap as a horizontal bar, show block headers, sizes and status; for buddy, draw binary split tree and label block sizes and addresses.
- Step-by-step traces for allocation/free/GC with final fragmentation numbers and justification of coalescing decisions.
Quick check
- Define internal fragmentation in one sentence.
- In the buddy system with min_block=32, what block size will satisfy a request for 70 bytes (assume 8 bytes overhead and 8‑byte alignment)?
- Name one advantage and one disadvantage of reference counting. Answers: 1) Internal fragmentation is the total wasted bytes inside allocated blocks because the allocator gives larger blocks than requested. 2) Requested+overhead = 78 → round up to 8 → 80 → next power-of-two block sizes (32,64,128) → 128 bytes. 3) Advantage: immediate reclamation when count reaches zero (predictable); disadvantage: cannot reclaim cyclic garbage.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?