Automatic Memory Management

Outline

Why Automatic Memory Management?

Type Safety and Memory Management

Automatic Memory Management

The Basic Idea

Dead Objects

Garbage

Reachability is an Approximation

Cool Garbage

Garbage Analysis

Tracing Reachable Values

Reachability

A Simple Example

Elements of Garbage Collection

Mark and Sweep

Mark and Sweep Example

The Mark Phase

let todo = { all roots }
while todo is not empty
    pick v in todo
    remove v from todo
    if mark(v) = 0 then
        mark(v) <- 1
        let v1, ..., vn be pointers contained in v
        add pointers to todo

The Sweep Phase

The Sweep Phase

p <- bottom of the heap
while p < top of the heap
    if mark(p) = 1 then
        mark(0) <- 0
    else
        add block p...(p + sizeof(p)-1) to free list
    p <- p + sizeof(p)

Mark and Sweep Analysis

Mark and Sweep Details

Mark and Sweep Evaluation

Stop and Copy

Stop and Copy

Stop and Copy Example

Implementing Stop and Copy

Implementing Stop and Copy

Stop and Copy Algorithm

while scan not equal to alloc
    let O be the object at scan pointer
    for each pointer p contained in O
        find O' that p points to
        if O' is without a forwarding pointer
            copy O' to new space (update alloc pointer)
            set first word of 0' to point to the new copy
            change p to point to the new copy of O'
        else
            set p in O equal to the forwarding pointer
    increment scan pointer to the next object

Stop and Copy Details

Stop and Copy Evaluation

Why Doesn’t C Allow Copying?

Conservative Garbage Collection

Reference Counting

Implementing Reference Counts

Reference Counting Evaluation

Garbage Collector Evaluation

Garbage Collector Evaluation

Real Life Examples

Summary