Memory allocation and compiling control structures
How compilers and runtime systems allocate memory (static, stack, heap) and translate high-level control structures (if, loops, switch, boolean expressions) into low-level code, with rules for activation records, backpatching and short‑circuit code generation.
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 and compiling control structures are core tasks in system programming and compiler construction. An engineer uses these when implementing language runtimes, writing low-level code (device drivers, OS modules), or building a compiler/backend that must produce correct, efficient layout and control-flow code.
Key ideas
Definitions (each bold term defined before use):
- Memory allocation: the process of reserving a region of memory for use by a program. It includes allocation policies, lifetime, and deallocation.
- Lifetime: the time period during program execution when a storage location holds a meaningful value.
- Scope: the region of source code where a name (variable, function) is visible.
- Static allocation: allocation done before program starts; storage persists for the whole program (examples: global variables, static local variables).
- Thread-local storage (TLS): allocation done before thread start; each thread has its own instance; lifetime is the thread's lifetime; typically placed in a TLS segment.
- Stack allocation: allocation in a last-in, first-out region called the call stack; used for function parameters, return address, local variables with compile-time size.
- Heap allocation: dynamic allocation at runtime using requests (e.g.,
malloc); lifetime controlled by programmer or GC. - Activation record (stack frame): the block of stack memory created for one call of a function, containing its return address, saved registers, parameters, local variables and bookkeeping.
- Control-flow graph (CFG): a directed graph whose nodes are basic blocks (straight-line code sequences) and edges are possible control transfers. Draw nodes as labeled boxes and arrows for edges.
- Backpatching: delaying filling of jump targets (addresses/labels) until those targets are known; maintain lists of unresolved jumps and patch them once labels are defined.
- Short-circuit evaluation: evaluating a boolean expression so that evaluation stops as soon as the result is determined (e.g., in
A && BifAis false,Bis not evaluated).
Exact statements / laws and assumptions:
- Storage classification law: In C-family languages, each object has one storage duration: static, thread, automatic, or allocated (heap). For exams, map these to typical regions: static (globals and static locals), thread-local (TLS segment; one instance per thread), stack/automatic (activation record), and heap/allocated (malloc/new). Assume no special storage like memory-mapped devices. This classification governs lifetime; actual placement and addressing are ABI/optimizer-dependent (e.g., register allocation may elide a stack slot).
- Activation record layout (assumed conventional caller-saved/right-to-left argument order; exact layout is calling-convention dependent): An activation record typically contains: optional saved frame pointer, return address, saved registers as required, arguments (incoming), local variables, temporaries, and any outgoing argument space. Offsets are computed from a stable base (frame pointer or stack pointer), and some ABIs omit the frame pointer (frame-pointer omission).
- Offset arithmetic for arrays and records: For an array with element size s (bytes) and base address B, address of element i (0-based) is:
Addr(B[i]) = B + i·s. This assumes contiguous allocation and fixed element size. - Backpatching invariant: if a list L holds unresolved jump sites, and label
L1is placed now, then patching every entry in L with the address ofL1makes the control flow consistent; algorithmic complexity depends on how you represent lists (use linked lists to append in O(1)).
What to draw (diagrams exam usually expects):
- Stack frame diagram for a single function call: draw a vertical rectangle labelled "Stack (grows downward)"; inside, from top (higher addresses) to bottom: caller area (caller locals/temps), return address, saved frame pointer, local variables, temporaries, outgoing argument space. Label each field and annotate offsets relative to frame pointer FP (e.g., FP+4 = return address, FP-4 = first local). If using a different convention, label accordingly.
- Control-flow graph for an
if-elseandwhile: draw three basic blocks forif(cond),then,elseand edges: cond->then (if true), cond->else (if false), then->join, else->join. Forwhile, draw loop header (cond), body, and edge from body back to header and exit edge from header to next.
Detailed steps compilers use to translate control structures (high level):
- Parse source to AST.
- Build basic blocks and CFG.
- Generate intermediate code (three-address code) for expressions and statements. For boolean expressions, prefer conditional jumps (
ifFalse x goto L) to implement short-circuit. - Perform backpatching: emit jump instructions with placeholders and maintain lists of unresolved addresses.
- Allocate registers and stack slots (storage allocation phase). Decide which temporaries go to registers vs stack and assign offsets for local variables.
- Emit target assembly using calling convention and activation record layout.
Examples of three-address code patterns to remember (syntax):
- Assignment:
t = x + y - Conditional jump:
if x < y goto L1 - Unconditional jump:
goto L2 - Label:
L1: - Function call:
param a,call f, n,t = ret(alternative TAC:t = call f, n)
Formulas
Addr(B[i]) = B + i · s — B is base address (bytes), i is element index (unitless), s is element size in bytes (SI unit: B, bytes). Applies to contiguous arrays.
size_of_array = n · s — n is number of elements, s is size per element (bytes).
offset(field) = sum(sizes of previous fields + padding before this field); Addr(field) = base_struct + offset(field) — computes byte offset of a struct field (relative to the base) and its address; units: bytes; must include alignment padding.
Activation-record offsets (example convention):
FP + 0 = previous FP (or depends on convention)
FP + 4 = return address (assumes 4-byte word)
FP - 4 = first local (bytes)
Syntax to remember (C-style):
void* malloc(size_t size); — allocate size bytes on heap; returns pointer or NULL; returned block is uninitialized and suitably aligned for any object type.
void free(void* ptr); — free memory returned by malloc; passing NULL is a no-op; double free is undefined behavior.
sizeof(type_or_expr) — compile-time (or some cases runtime) size in bytes.
new Type / delete ptr — C++ dynamic allocation and deallocation.
Worked examples
Example 1 — Memory layout calculation (numerical)
Assume a 32-bit target where int = 4 B, pointer = 4 B, char = 1 B, and no compiler-added packing beyond natural alignment. Given:
- Global array
int G[10]; - Function
f(int n)with localint a[3]; char c; - During execution, one
malloc(100)call returns a 100-byte block. Compute sizes and offsets. Steps:
Gtotal size = 10 · sizeof(int) = 10 · 4 = 40 B.- In
f, localasize = 3 · 4 = 12 B.csize = 1 B. With natural alignment,cwill be padded to align next objects; assume no other locals afterward, so frame needs at least 12 + 1 = 13 B. Align stack to 4 B => total locals area = 16 B. - Heap block size = 100 B as allocated. Final answers: Global G = 40 B; Frame locals area = 16 B; Heap block = 100 B. (If target is 64-bit or compiler adds different padding, results change — verify sizes for your system.)
Example 2 — Translate if (A < B) C = D + E; else C = D - E; to three-address code and assembly-like steps
- Three-address code: t1 = A < B if t1 goto L1 goto L2 L1: t2 = D + E C = t2 goto L3 L2: t3 = D - E C = t3 L3: (join)
- Backpatch: when generating
ifwe emitif t1 goto ?andgoto ?, push their addresses into liststrueListandfalseList; when L1 and L2 are defined, patch jumps. - Assembly-like (pseudo x86 style, assume registers r1..r3): cmp A, B jl L1 ; jump if less ; else mov r1, D sub r1, E mov C, r1 jmp L3 L1: mov r1, D add r1, E mov C, r1 L3: Final answer: TAC and patched jump targets as above.
Example 3 — Short-circuit if (X && Y) S; traced to jumps
- For
X && Y: evaluate X; if false, skip evaluating Y and skip S. - TAC style using boolean-to-jump:
if X goto L2;goto L1;L2: if Y goto L3;goto L1;L3: S;L1:(exit) - This avoids computing Y when X is false. Answer: Short-circuit code uses conditional jumps and preserves semantics while avoiding unnecessary evaluation.
Common mistakes
- Emitting unconditional
gototoo early and breaking short-circuit behaviour. - Not freeing heap memory causing leaks (or freeing stack/invalid addresses causing UB).
- Using absolute addresses instead of relative offsets in activation records; hard to link/relocate.
- Thinking
sizeofyields a compile-time constant for all expressions (in C,sizeofof a VLA is evaluated at runtime; in C11 VLAs are optional, and in standard C++ VLAs are not supported).
For your exam
Typical question types:
- Definitions and short notes: define static/stack/heap, activation record, backpatching. What full marks include: clear definitions, example, and where used in compilers/runtime.
- Derivations: calculate offsets in a struct/stack frame; derive address formula for array element. Full marks: show step-by-step offset additions and alignment considerations; draw diagram and label offsets.
- Numericals: compute memory used by globals/stack/heap for given code. Full marks: state assumptions (word size, alignment), show arithmetic with units (bytes), final numeric answers.
- Programs/algorithms: show three-address code and backpatching lists for control constructs; trace short-circuit evaluation. Full marks: correct TAC, correct placement of labels, clear backpatching steps and patch lists.
- Diagrams: draw CFG or stack frame. Full marks: correctly labeled nodes/fields and arrows showing flow or addresses.
Quick check
- What are the three common storage classes by lifetime?
- Give the address formula for array element B[i] (element size s).
- In short-circuit evaluation of
A || B, when isBnot evaluated? Answers: 1) Static, stack, heap. 2)Addr(B[i]) = B + i · s. 3)Bis not evaluated ifAis true (sinceA || Balready true).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?