Storage allocation strategies
Storage allocation strategies: how compilers and runtimes place and reclaim memory (static, stack/activation records, heap allocation algorithms, fragmentation, buddy and free-list schemes, garbage collection) and how to analyse them for exams.
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
Memory allocation decides where program data (variables, objects, activation records) live at run-time. Engineers use storage-allocation strategies in compiler back ends (activation record placement, static vs dynamic allocation), run-time systems (heap managers, garbage collectors) and OS-level memory managers to get correct programs and good performance (low fragmentation, fast allocation and deallocation).
Key ideas
Start with a clear meaning for each term before use.
- Memory block: a contiguous region of address space that can hold program data. When we say a block of size 64 bytes we mean 64 consecutive bytes of addresses.
- Allocation: action of reserving a memory block for a program object. Deallocation: returning a block to the free pool.
- Static allocation: storage assigned at compile/link time and fixed for the whole program run (for example the global data area). Static allocation means the addresses and sizes are determined before execution. Feasible only when all object sizes are fixed and lifetimes are known at compile time (e.g., no recursion and no variable-sized locals).
- Automatic (stack) allocation: storage assigned and freed in strict LIFO order during function calls; each function activation gets an activation record (also called stack frame) on the stack. The stack grows and shrinks; allocation is by moving the stack pointer (fast, constant-time). Typical activation record fields include: return address, control/dynamic link, access/static link (for nested scopes), saved registers, locals, temporaries, and space for outgoing arguments.
- Dynamic (heap) allocation: storage requested at run-time with variable lifetimes; uses a heap manager (allocator) which finds free blocks and returns addresses; deallocation can be explicit (free) or implicit (garbage collection).
- External fragmentation: unused memory appears as many small free blocks that are not usable for large requests even if total free memory is sufficient. Definition (exact): given a heap with set of free blocks F = {f1,f2,...}, external fragmentation for a request of size r is "no fi ≥ r while sum(fi) ≥ r". Often measured as the total free memory in blocks smaller than a threshold divided by total free memory.
- Internal fragmentation: wasted space inside an allocated block because allocation unit is larger than requested size (e.g., rounding up to alignment or size class). Exact measure: internal fragmentation = (allocated size − requested size) summed over allocations.
- First-fit, Best-fit, Worst-fit: placement algorithms that search the free list for a block to satisfy a request. First-fit: choose first free block large enough. Best-fit: choose smallest free block that fits. Worst-fit: choose largest available block.
- Free-list: data structure linking free blocks. Variants: singly-linked, doubly-linked, segregated free lists (separate lists per size class).
- Bump-pointer allocation (also called linear allocation): maintain a pointer to the next free address; allocation increments pointer by requested size (rounded up). Very fast (O(1)), but deallocation normally must free whole region or use GC.
- Buddy system: divide memory into power-of-two sized blocks. To satisfy a size request, round up to next power-of-two block; split larger blocks recursively into equal buddies until the block size matches; on free, coalesce with buddy if the buddy is free. Guarantees easy coalescing and bounded fragmentation (at most factor 2 internal fragmentation in size).
- Segregated free lists: maintain multiple free lists, each for a range of sizes (size classes). Can give faster selection and often lower fragmentation than a single list, depending on workload and implementation.
- Splitting and coalescing: when allocating from a bigger free block we can split it into allocated part + smaller free remainder. When freeing, if neighboring free blocks exist we can coalesce into a larger block to reduce external fragmentation.
- Garbage collection (GC): automatic reclamation of heap storage that is no longer reachable from program roots (registers, stack, global references). Main families: reference counting, mark-and-sweep, copying (semi-space), mark-compact, and generational GC. Exact behaviour and cost assumptions should be stated when used.
- Reachability: an object is reachable if there exists a chain of pointers from a root to that object. GC reclaims unreachable objects.
What to draw (exam diagrams): draw a horizontal line labelled addresses from low (left) to high (right). Mark segments: code, static (globals), heap (grows right), free blocks (label sizes and whether free or allocated), stack (grows left) with frames labelled by function name and local variables. For buddy system draw a binary tree where root is entire memory block and children are halves; label nodes with sizes and allocated/free status.
Exact laws / statements students are asked for:
- Statement: Bump-pointer allocation runs in O(1) time per allocation, but requires either manual deallocation of whole region or GC for arbitrary deallocation. Assumption: contiguous free space is available; any per-object padding is only due to alignment.
- Statement: In the buddy system, each coalescing step with the buddy is O(1) time given a way to find the buddy (address XOR block_size). Assumption: blocks aligned to their size boundary.
- Statement: Reference counting reclaims an object exactly when its reference count drops to zero, but cannot collect objects involved in cycles (counterexample: two objects pointing to each other only). Assumption: counts updated on each pointer store.
Formulas
InternalFrag = (sum over allocated blocks (allocated_size - requested_size)) / (sum over allocated blocks allocated_size) — fraction (unitless). Applied when allocations are rounded up.
ExternalFrag(request r) = 1 if (no free block size >= r) AND (sum of free sizes >= r) else 0 — indicates whether external fragmentation prevents a request of size r. Another common metric is ExternalFrag_ratio = 1 − (size of largest free block) / (total free memory), over the current heap state.
Utilization = (total requested bytes in use) / (total memory managed) — unitless fraction; measures useful memory fraction.
Buddy_buddy_address = address XOR block_size — computes buddy start address when blocks are aligned to block_size; addresses in bytes; applies in buddy system.
AllocationTime_firstfit = O(n_free) — where n_free is number of free blocks (worst-case). Similarly, best-fit and worst-fit are O(n_free) unless ordered or indexed structures (e.g., size-ordered lists, segregated lists, or trees) are used.
AllocationTime_bump = O(1) — applies to bump-pointer allocation without free operations.
Cost_mark_and_sweep ≈ O(heap_size + reachable_objects) for a full collection — traverses reachable objects then scans heap to reclaim.
Worked examples
Example 1 — First-fit, fragmentation metrics (exam-style): Initial single free block of 1000 bytes. Requests sequence (in order): 100, 200, 50, 180. Then free the second block (200), then request 170. Steps:
- Allocate 100 using first-fit: take first free block of 1000, split into allocated 100 and free 900. Remaining free blocks: [900].
- Allocate 200: first free 900 → allocate 200, free remainder 700. Free blocks: [700].
- Allocate 50: from 700 → allocate 50, free 650. Free blocks: [650].
- Allocate 180: from 650 → allocate 180, free 470. Free blocks: [470].
- Free the 200-byte block (the second allocation): free blocks now [200,470] (order depends on implementation; assume freed block placed before later block). External fragmentation? If a later request is 300, total free = 670 ≥ 300 but no single block ≥300, so external fragmentation prevents allocation.
- Now request 170: first-fit finds first free block 200 which fits; allocate 170 there leaving 30. Final free blocks: [30,470]. Compute internal fragmentation: only blocks with rounding cause internal waste; here assume exact sizes used so internal fragmentation is 0. Utilization: allocated total = 100+50+180+170 = 500 bytes. Total managed memory = 1000. Utilization = 500/1000 = 0.5 (50%). Final answer bold: Utilization = 50%; external fragmentation example: request 300 fails after step 5 even though total free = 670 (200+470) — demonstrate external fragmentation.
Example 2 — Buddy system trace (exam-style): Assume total heap 1024 bytes (one block). Requests: A=200, B=300, C=100. Steps:
- Request A=200 → round up to next power of two: 256. Split 1024 → two 512s → split first 512 → two 256s → allocate one 256 to A. Free buddies: one 256 (from same split), one 512 (the other half). Representation: blocks free: [256,512].
- Request B=300 → round up to 512. Find free 512 and allocate it to B. Free blocks: [256].
- Request C=100 → round up to 128. From 256 free block: split 256 → two 128s → allocate one 128 to C; free blocks: [128].
- Free B (512): on freeing, check buddy of that 512 — buddy is the 512 that was split earlier? In our trace B's buddy is the first 512 (which was split into 256+256), so it is not free as it contains used 256 and free 256; therefore no coalesce to 1024. Free blocks become [512 (from B),128]. If we later free A (the allocated 256), it coalesces with its free 256 buddy into a 512; if that 512's buddy (the freed B block) is also free, they coalesce back to 1024. Final note (bold): Allocated sizes were 256(A), 512(B), 128(C). Buddy coalescing depends on alignment and buddy free status.
Example 3 — Mark-and-sweep small GC trace: Heap objects: O1 at addr 100 (points to O2), O2 at 200 (points to O3), O3 at 300 (no pointers), O4 at 400 (points to O4 itself cyclic). Roots: variable R1 points to O1; variable R2 is null. Steps:
- Mark phase: start from roots: R1 → O1 mark; O1 → O2 mark; O2 → O3 mark; O3 no pointers. O4 is not reachable from roots (though self-cycle). Marked set = {O1,O2,O3}.
- Sweep phase: scan heap; reclaim unmarked objects: O4 reclaimed. Reclaimed cycles are removed: reference counting would not have reclaimed O4. Bold final: Objects O1,O2,O3 live; O4 collected.
Common mistakes
- Forgetting alignment overhead (padding) when calculating internal fragmentation or activation record sizes.
- In buddy examples: not aligning addresses to block sizes and then incorrectly computing buddy by address XOR size.
- Saying garbage collection always costs O(n) per allocation — GC cost is amortized and depends on algorithm (e.g., bump-pointer + copying GC gives very fast allocation with periodic collections).
- Treating reference counting as complete GC (it cannot collect cyclic garbage unless augmented with cycle detection).
For your exam
Types of questions:
- Definitions and short notes: define static/stack/heap allocation, fragmentation types, and describe bump-pointer, free-list, buddy system, segregated lists.
- Derivations and proofs: show how buddy buddy address is computed (use XOR), argue worst-case fragmentation bounds for buddy (at most factor 2 waste per allocation due to power-of-two rounding), show time complexity of first-fit vs bump-pointer.
- Algorithm traces: perform first-fit, best-fit, or buddy allocation on a small memory diagram; perform mark-and-sweep or reference-counting update on a small object graph.
- Design/compare: choose an allocator for a given workload (many small short-lived objects vs large long-lived objects) and justify with fragmentation and speed arguments. What full-marks answers include:
- Correct definitions with bold term usage, clear assumptions (alignment, initial heap layout), step-by-step traces with sizes and addresses, and final metrics (utilization, fragmentation) with units.
- Diagrams: linear memory with addresses or buddy binary tree as instructed above.
Quick check
- What is internal fragmentation?
- How does the buddy system find a block's buddy address (operation)?
- Give one advantage and one disadvantage of bump-pointer allocation. Answers: Internal fragmentation is wasted space inside allocated blocks when allocation size is rounded up; buddy address = address XOR block_size; bump-pointer advantage = O(1) allocation time, disadvantage = no easy per-object deallocation (needs GC or region free).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?