next up previous contents
Next: 13.2.1 Mark-and-Sweep Garbage Collection Up: 13 Garbage Collection Previous: 13.1 Storage Allocation   Contents

13.2 Automatic Garbage Collection

Heap-allocated records that are not reachable by any chain of pointers from program variables are considered garbage. All other data are 'live'. This is a very conservative approach but is always safe since you can never access unreachable data. On the other hand, it may keep objects that, even though reachable, they will never be accessed by the program in the future.

With automatic storage management, user programs do not reclaim memory manually. When the heap is full, the run-time system suspends the program and starts garbage collection. When the garbage collection is done, the user program resumes execution:

char heap[heap_size];
int end_of_heap = 0;
void* malloc ( int size ) {
    if (size+end_of_heap > heap_size)
         GC();            // garbage collection
    void* loc = (void*) &heap[end_of_heap];
    end_of_heap += size;
    return loc;