The model
The heap holds objects whose lifetimes are not tied to one simple lexical scope. A runtime allocator reserves space, initializes an object, and returns a reference. Garbage collection reclaims memory that is no longer reachable under the collector’s object graph and root rules.
A concrete walk-through
A tracing collector starts from roots such as active stacks and global references, follows pointers, and marks reachable objects. A copying collector can move live objects into a new region and update references, while a generational collector uses the observation that many objects die young to focus collection work.
Costs and failure cases
Garbage collection does not prevent leaks when the program keeps unnecessary references reachable. Collection pauses, write barriers, fragmentation, and allocation rate affect latency. Manual memory management avoids some runtime work but transfers lifetime and aliasing correctness to the programmer.
Check your understanding
A cache retains every response forever in a global map. Explain why the collector cannot reclaim those entries and propose a retention policy that bounds memory by behavior rather than hope.