Sub topic 5
Heap Allocation, Garbage Collection, and Intermediate Code
Assume you know C-style pointers, stacks, graphs, and basic compiler phases. This chapter connects runtime heap management with the compiler’s use of intermediate representations (IRs).
Heap allocation and garbage collection basics
The heap is a region of runtime memory used for objects whose lifetime or size cannot be determined by simple stack rules. A program requests heap storage with an allocator such as malloc. It releases that storage with free, or a garbage collector reclaims it automatically.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *values = malloc(3 * sizeof *values);
if (values == NULL) return 1;
values[0] = 10;
values[1] = 20;
values[2] = 30;
printf("%d\n", values[1]);
free(values);
return 0;
}A heap allocator records which blocks are free and which are in use. Allocation can be fast, but repeated allocation and release can create fragmentation, where enough total space exists but not in one usable block.
A garbage collector (GC) finds objects that the program can still reach. These objects are called live. Objects that cannot be reached are garbage and may be reclaimed.
A tracing collector commonly begins at roots, such as stack variables, global variables, and registers. It follows pointers from the roots. A mark-and-sweep collector marks reachable objects, then sweeps through the heap and releases unmarked objects.
Reference counting is another technique. Each object stores the number of incoming references and is reclaimed when that count reaches zero. It handles reclamation incrementally, but a cycle of objects can keep all counts above zero.
| Method | Main idea | Common limitation |
|---|---|---|
| Manual management | The programmer calls `free` | Leaks and dangling pointers |
| Reference counting | Reclaim when count becomes zero | Cycles may remain |
| Tracing GC | Reclaim objects unreachable from roots | Pauses and runtime overhead |
Why compilers use intermediate code
An intermediate representation is a compiler-internal form between source code and machine code. It separates language-specific parsing from target-specific instruction generation.
For example, the expression a = b * (c + d) can become:
t1 = c + d
t2 = b * t1
a = t2This three-address code makes evaluation order and temporary values explicit. The compiler can optimize this form, divide it into basic blocks, perform data-flow analysis, and later translate it to different processors.
The same IR can represent source languages with different syntax and target machines with different registers. This reuse reduces compiler complexity.
Exercise
An object is not referenced by any root but is part of a cycle with another object. Will reference counting necessarily reclaim it? Which common collector can reclaim it?
Show answer
No. Each object in the cycle can have a nonzero reference count. A tracing collector can reclaim the cycle because neither object is reachable from a root.