5.1.17 · D3C Programming

Worked examples — Heap fragmentation

2,360 words11 min readBack to topic

This is the "roll up your sleeves" child of Heap fragmentation. The parent gave you the ideas — external vs internal fragmentation, coalescing, the block-size formula. Here we drive every one of those ideas through concrete numbers, and we deliberately hit every corner case the topic can throw at you: each sign of the block formula, zero-size and degenerate inputs, the limiting behaviour when requests get huge, a real-world word problem, and an exam-style trick.

Before any example, let us re-earn the two tools we lean on, in plain words.


The scenario matrix

Every worked example below is tagged with the matrix cell it covers, so you can see the whole space is filled.

Cell What varies Extreme it probes Example
A External-fail free total ≥ request, holes non-adjacent the classic NULL-despite-free Ex 1
B Coalesce-save free in adjacent order holes merge back to one Ex 2
C LIFO vs random same allocs, two free orders order decides fate Ex 3
D Internal overshoots a boundary worst-case waste Ex 4
E Internal lands exactly on a boundary zero-waste degenerate Ex 5
F Zero / tiny input header-only block Ex 6
G Limiting behaviour large waste fraction Ex 7
H Word problem game-server churn real-world external frag Ex 8
I Exam twist "total free = request ⇒ success?" disprove with a counter-layout Ex 9

We touch every sign of (positive in D, zero in E), zero input (F), the large limit (G), both free orders (C), and the two flavours of fragmentation (external: A,B,C,H,I; internal: D,E,F,G).


Ex 1 — Cell A: external fragmentation forces NULL

Figure — Heap fragmentation

Ex 2 — Cell B: coalescing rescues the same request


Ex 3 — Cell C: same allocations, two destinies

Figure — Heap fragmentation

Ex 4 — Cell D: internal fragmentation, worst-ish case


Ex 5 — Cell E: the zero-waste boundary case


Ex 6 — Cell F: zero-size request malloc(0)


Ex 7 — Cell G: the limiting behaviour, huge request


Ex 8 — Cell H: real-world word problem

Figure — Heap fragmentation

Ex 9 — Cell I: the exam twist (disprove a plausible claim)

Recall Quick self-test

Success of malloc(n) depends on which quantity? ::: The size of the largest single contiguous hole, not total free bytes. For r=20, h=8, a=16, the wasted bytes are? ::: 12 For r=24, h=8, a=16, the rounding waste is? ::: 0 (only the 8-byte header is overhead) malloc(0) with h=8, a=16 carves a block of size? ::: 16 bytes (all overhead) As r grows large, W/B tends to? ::: 0


Connections

  • Heap fragmentation — the parent topic these examples drill
  • malloc and free — the first-fit allocator every example simulates
  • Stack vs Heap — why LIFO (Ex 3) never fragments
  • Memory alignment — the in the block formula (Ex 4–7)
  • Pool allocator / Arena allocator — the fixes for Ex 8
  • Garbage collection — compaction that would rescue Ex 8
  • Memory leaks — contrast: leaked ≠ fragmented