Garbage collection (GC) is an automatic memory management process that reclaims heap memory occupied by objects no longer reachable or needed by a program. By tracking object references and periodically freeing unreachable memory, GC eliminates common bugs such as memory leaks and dangling pointers without requiring explicit deallocation by the programmer. It is a core feature of languages including Java, Python, Go, C#, and JavaScript, with algorithms such as mark-and-sweep, reference counting, and generational collection.
| Algorithm | How It Works | Pause Time | Language Examples |
|---|---|---|---|
| Reference Counting | Tracks refs to each object; frees at zero | Low (incremental) | Python (CPython), Swift |
| Mark-and-Sweep | Marks reachable objects; sweeps unmarked | Stop-the-world pauses | Early Java, Go |
| Generational GC | Separates objects by age; collects young often | Low for young gen | Java (JVM), .NET CLR |
| Tri-colour Marking | Concurrent mark using white/grey/black sets | Very low | Go (post-1.5), V8 |
| Compacting GC | Moves surviving objects to eliminate fragmentation | Moderate pause | Java G1, .NET |
Wikimedia Commons, CC BY-SA
Memory allocation is the process by which a program reserves a portion of a computer's RAM for its variables, data structures, and execution context. Allocation can be static (at compile time), automatic (on the call stack), or dynamic (on the heap at runtime using functions like malloc in C or new in C++/Java). Proper memory management is critical for performance and preventing bugs such as memory leaks, buffer overflows, and dangling pointers.
A pointer is a variable that stores the memory address of another variable rather than a data value directly. Pointers enable direct memory access and manipulation, dynamic memory allocation, and efficient passing of large data structures without copying. They are central to languages such as C and C++, and understanding them is key to systems programming, data structure implementation, and performance-critical software.
The term "garbage collection" was coined by John McCarthy in 1959 during the development of LISP, where he used the metaphor of collecting unused memory "garbage" to reclaim storage for reuse.