Also known as: garbage collection, GC
Garbage collection (GC) is a form of automatic memory management in which the language runtime reclaims memory the program can no longer reach, so the programmer never has to free it by hand.1
How it works
The runtime periodically determines which heap objects are still reachable by following references from a set of roots (stack variables, globals, registers). Anything with no path from the roots is garbage and its memory is reclaimed. Common strategies include mark-and-sweep (mark reachable objects, sweep the rest), generational collection (collect short-lived objects more often), and reference counting (track how many references point at each object).1
Trade-offs
GC eliminates entire classes of bugs that plague manual memory code — use-after-free, double-free, and many memory leaks — and removes a great deal of boilerplate. The price is runtime overhead and occasional pauses (historically “stop-the-world” collections),1 which is why latency-sensitive and systems languages such as C and C++ leave memory to the programmer, and why Rust achieves safety at compile time without a collector at all.
In practice
Most mainstream languages are garbage-collected, including Go, Java, Python, and C#. Their collectors have grown sophisticated enough that GC pauses are a non-issue for the vast majority of applications.
Sources
-
Garbage collection (computer science) — Wikipedia, on reachability-based reclamation, collection strategies, and the overhead/pause trade-offs. ↩ ↩2 ↩3