What is Garbage Collection?
Garbage collection automatically reclaims memory that a program no longer uses, freeing developers from manual memory management.
Garbage collection (GC) is automatic memory management. Instead of the programmer manually freeing memory, the language runtime tracks which objects are no longer reachable and reclaims that memory for reuse. Languages like Java, Python, Go, and JavaScript use it.
How It Works:
- The program allocates memory for objects
- The garbage collector periodically checks which objects are still reachable
- Objects no longer referenced are considered "garbage"
- Their memory is freed and made available again
Common Strategies:
- Reference counting: Track how many references point to each object
- Mark-and-sweep: Mark reachable objects, then sweep away the rest
- Generational GC: Collect short-lived objects more often than long-lived ones
Trade-offs:
- Pro: Prevents many memory leaks and dangling-pointer bugs
- Pro: Simpler, safer code
- Con: Adds runtime overhead and occasional pauses
FAQ
Does garbage collection prevent all memory leaks?
No. You can still leak memory by keeping references to objects you no longer need (e.g. in a growing cache or global list). The GC only frees truly unreachable objects.
Why do some languages avoid garbage collection?
Languages like C, C++, and Rust favor manual or compile-time memory management for predictable performance and no GC pauses, which matters for systems and real-time software.