Interview prompt
Explain heap allocation and garbage collection to an engineer who understands the surrounding system but has not used this technique. Walk from its contract to a concrete operation, then discuss where it fails or becomes expensive.
A strong answer
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 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.
A complete answer also calls out the assumptions that control correctness. 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.
Close by describing one representative test or measurement. 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.
Follow-up questions
Answer the follow-ups in the frontmatter. Use the linked article for the concept and the trace to make the explanation concrete.