Every running program is a small economy of memory. It asks the system for space to hold an object, wires that object to others, and moves on. But space is finite — sooner or later someone has to give it back. Do it too eagerly and you free memory another part of the program still needs (a crash); do it too late, or never, and the program slowly swells until it falls over (a leak).
Garbage collection automates the hard half of that bargain. The key insight, due to John McCarthy in 1960 for the Lisp language, is deceptively simple: an object is garbage not when you say so, but when nothing can reach it anymore. If no chain of references leads from a live variable to an object, your code can never touch it again — so its memory is safe to reclaim.
That turns memory management into a question about a graph: starting from the roots (local variables, globals, the call stack), which objects are still reachable? Everything reachable lives; everything else is garbage. The most classic algorithm for answering it is mark-and-sweep.
Comments
Loading comments...