The objects that a program can access directly are those objects which are referenced by local vari-ables on the processor stack, or by any global/static variables that refer to objects, or by variables in CPU registers. In the context of garbage collection, these variables are called the roots. An object is indirectly accessible if it is referenced by a ?eld in some other (directly or indirectly) accessible object. An accessible object is said to be live. Conversely, an object which is not live is garbage.
Note that heap objects which are live are indirectly accessible from the roots or other heap objects. The idea of mark-sweep is relatively straightforward. We start at the roots, and recursively visit every object accessible through pointers, marking them as live. At the end of the process, every thing not marked is considered garbage and will be deleted. Notice that mark-sweep can perform lazy garbage collection, in the sense that it does not necessarily need to remove the garbage immediately.
Note thatmark-sweep does not clean upmemory which is allocated, but simply never used. Also, periodically we have to visit all objects recursively, starting from the roots. For a large program, this will be slow. This is a problem with the traditional mark-sweep algorithm.