Previous      Up      Previous     Course Home   e-mail

2.2 Mark and Sweep

Mark and Sweep   

Mark and sweep is one of the earliest and best-known garbage collection algorithms.


Assumptions   

The core assumptions of mark and sweep are:


The Mark and Sweep Algorithm   

With those assumptions, the mark and sweep garbage collector is pretty simple:

void markAndSweep()
{
 // mark
 for (all pointers P on the run-time stack or
   in the static data area )
  {
    mark *P;
  }

 //sweep
 for (all objects *P on the heap)
   {
     if *P is not marked then
        delete P
     else
        unmark *P
   }
}

template <</span>class T>
void mark(T* p)
{
  if *p is not already marked
    {
      mark *p;
      for (all pointers q inside *p)
        {
          mark *q;
        }
     }
}

The algorithm works in two stages.


Mark and Sweep Example   

As an example, suppose that we start with this data.

Then, let’s assume that the local variable holding the list header is destroyed.

Mark and Sweep Example II   


We first come to the pointer to Boston, and recursively invoke mark() on that. But Boston is already marked, so we return immediately to the N.Y. call. Continuing on, we find a pointer to Wash DC. and invoke mark() on that.

The Wash DC object has not been marked yet, so we mark it and then iterate over the pointers in Wash DC. We first come to the pointer to Boston, and recursively invoke mark() on that. But Boston is already marked, so we return immediately to the N.Y. call. Again, that object is already marked so we immediately return to the earlier N.Y. call. That one has now visited all of its pointers, so it returns to the first Boston call.

The Boston call resumes iterating over its pointers, and finds a pointer to Wash DC. It calls mark() on that pointer, but Wash DC has already been marked, so we return immediately. The Boston call has now iterated over all of its pointers, so we return to the main mark and sweep algorithm.

That algorithm continues looking at pointers on the activation stack. We have a pointer to N.Y., and call mark() on that. But N.Y. is already marked, so we return immediately.

Mark and Sweep Example III   

Once the mark phase of the main algorithm is complete,


The Sweep Phase   

In the sweep phrase, we visit each object on the heap.


Assessing Mark and Sweep   

In practice, the recursive form of mark-and-sweep requires too much stack space.


 Previous      Up      Previous     Course Home   e-mail