Course contentsShow
← Computer Science
Lesson 2094 of 2,87247. Memory Management in LanguagesFree lesson

What is Garbage Collection?

Automatic memory reclamation: identifying and freeing unused objects without programmer intervention.

What is Garbage Collection?

You'll learn: How modern languages automatically reclaim memory without requiring you to manually free objects.

The Core Idea

Garbage Collection (GC) is an automatic memory management system that identifies objects your program no longer uses and reclaims their memory—without you writing explicit free() or delete calls. Instead of tracking lifetimes yourself (like in C's manual memory management), the runtime does it for you.

How It Works Conceptually

Think of garbage collection like an automated cleaning service for your program's memory. The GC periodically scans through memory, identifies "garbage" (objects no longer reachable from your program), and returns that space to the available memory pool.

Reachability is the key concept: if your program cannot possibly access an object anymore (no variables, no pointers, no references lead to it), that object is garbage. The collector traces from "roots"—active variables, stack frames, global references—and marks everything reachable as "live." Everything else can be safely reclaimed.

Why Garbage Collection Exists

Manual memory management (lessons 2084–2093) requires careful discipline. You've seen the pitfalls: memory leaks, dangling pointers, double-frees, use-after-free bugs. Garbage collection eliminates these entire classes of errors by making memory reclamation the runtime's responsibility, not yours.

Languages like Java, Python, JavaScript, Go, and C# all use garbage collection. You allocate objects freely; the GC worries about when to clean them up.

Key Takeaway:
Garbage collection automatically identifies and frees unreachable objects, eliminating manual memory management errors at the cost of runtime overhead and less predictable timing.