Sub topic 6
Heap allocation and garbage collection basics
This chapter assumes you know the runtime layout from earlier chapters (code, static data, stack, heap) and can read basic C and Python. It covers how the heap hands out memory, how that memory is reclaimed, and the standard GATE comparisons between reclamation schemes.
Why the heap exists
Stack frames die when their function returns. Some data must outlive the call that created it, such as a linked list node built inside a helper function. Data with that kind of lifetime goes on the heap. The program asks for a block (malloc, new) and gets back a pointer. The block stays valid until it is freed explicitly or until a garbage collector decides nothing can reach it any more.
Allocation with a free list
The memory manager keeps a free list of unused blocks. A request of n bytes is served by choosing a block of at least n bytes. If the block is larger, it is split and the remainder returns to the list. Common placement policies are:
- First fit: take the first block that is large enough. It is fast, but it tends to chop up the front of the list.
- Best fit: take the smallest block that is large enough. It leaves small remainders and needs a full scan unless the free blocks are kept sorted by size.
- Worst fit: take the largest block. It is rarely a good choice.
Freed blocks are coalesced with free neighbours. Without coalescing, the heap breaks into many small pieces.
External fragmentation means enough total free memory exists, but no single block is large enough. Internal fragmentation means a block is larger than the request because of rounding or alignment, so the extra space inside it is wasted.
Take free blocks of 100, 500, 200, 300 and 600 KB, in that order. Four requests arrive: 212, 417, 112 and 426 KB.
| Policy | 212 KB | 417 KB | 112 KB | 426 KB |
|---|---|---|---|---|
| First fit | 500 block | 600 block | 288 remainder | Fails: largest free block is 300 |
| Best fit | 300 block | 500 block | 200 block | 600 block |
Best fit satisfies all four requests here. First fit does not. This does not hold in general, because either policy can win on other inputs.
Errors with explicit deallocation
Manual freeing is fast but easy to get wrong:
- Memory leak: the last pointer to a block is lost before
free, so the block can never be reused. - Dangling pointer: a pointer is used after its block was freed. The memory may already belong to someone else.
- Double free: freeing the same block twice corrupts the free list.
Garbage collection removes the first two classes of error by freeing a block only when it is provably unreachable.
Reachability
A collector starts from the roots: global variables, registers and every pointer in live stack frames. An object is reachable if some chain of pointers leads to it from a root. Everything else is garbage. Reachability is an approximation of "will be used again". A reachable object that is never used is still kept, which is why leaks can happen even with a collector.
Reference counting
Each object stores a count of pointers to it. Assigning a pointer increments the new target's count and decrements the old one. At zero, the object is freed immediately, and its children's counts are decremented in turn.
- Advantage: reclamation is immediate and spread evenly through execution, with no long pauses.
- Disadvantage 1: every pointer update costs extra work.
- Disadvantage 2: cycles are never reclaimed. If object C points to D and D points to C, both counts stay at 1 after the last outside reference disappears.
Mark and sweep
This collector runs in two phases. The mark phase traces from the roots and sets a mark bit on every reachable object. The sweep phase scans the whole heap, returns unmarked objects to the free list and clears the mark bits. The following program simulates both phases:
class Obj:
def __init__(self, name):
self.name = name
self.refs = []
self.marked = False
def mark(roots):
stack = list(roots)
while stack:
o = stack.pop()
if not o.marked:
o.marked = True
stack.extend(o.refs)
def sweep(heap):
live = []
for o in heap:
if o.marked:
o.marked = False
live.append(o)
return live
a, b, c, d = Obj("A"), Obj("B"), Obj("C"), Obj("D")
a.refs = [b]
c.refs = [d]
d.refs = [c] # C and D form a cycle
heap = [a, b, c, d]
mark([a]) # only A is a root
heap = sweep(heap)
print([o.name for o in heap]) # ['A', 'B']The cycle of C and D is collected because it is unreachable from any root. Reference counting would have kept it.
The costs of mark and sweep are:
- Pauses: the program normally stops while the collector runs (stop-the-world).
- Sweep cost: it is proportional to the whole heap, live and dead objects together.
- Fragmentation: it leaves live objects where they are, so free space stays scattered.
Copying collection and compaction
A copying collector splits the heap into two halves. Allocation uses one half, called from-space. At collection time, reachable objects are copied to the other half, called to-space, and pointers are updated. The halves then swap roles. Live objects end up packed together, so fragmentation disappears and allocation becomes a pointer bump. The cost is proportional to live data only, but half the heap is unusable at any moment.
Generational collection builds on the observation that most objects die young. New objects go in a small young generation that is collected often and cheaply. Survivors are promoted to an older generation that is collected rarely.
Comparison
| Scheme | Reclaims cycles | Pause pattern | Fragmentation | Main cost |
|---|---|---|---|---|
| Reference counting | No | Small, frequent | Yes | Counter updates |
| Mark and sweep | Yes | Long | Yes | Whole-heap sweep |
| Copying | Yes | Proportional to live data | No | Half the heap unused |
Exercise
Free blocks in list order are 100, 500, 200, 300 and 600 KB. Requests of 212, 417, 112 and 426 KB arrive in that order. Which request fails under first fit, and why does best fit avoid the failure?
Show answer
Under first fit, 212 goes into the 500 block (leaving 288), 417 goes into the 600 block (leaving 183), and 112 goes into the 288 remainder (leaving 176). The free blocks are then 100, 176, 200, 300 and 183, so the 426 KB request fails. Best fit places 212 in 300, 417 in 500, 112 in 200 and 426 in 600, so every request succeeds.
Exercise
Object X points to Y, Y points to Z, and Z points to X. The only external pointer to X is then deleted. What happens under reference counting and under mark and sweep?
Show answer
Each of X, Y and Z still has a count of 1 from the cycle, so reference counting never frees them. Mark and sweep finds none of them reachable from any root, so it leaves them unmarked and the sweep reclaims all three.