Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Hard · Free

What is garbage collection? How do reference counting and mark-and-sweep differ?

FresherFundamentalsProgramming Fundamentals
Model answer

Garbage collection

Garbage collection (GC) reclaims heap memory for objects no longer reachable from GC roots (stack locals, static fields). The mutator (your code) allocates; the collector traces live objects and frees the rest.

ApproachIdeaTrade-off
Reference countingFree when count hits 0Cycles leak unless handled
Mark-and-sweepMark reachable, sweep restPause times; needs compaction
GenerationalYoung gen collected oftenAssumes most objects die young
diagram
roots → mark live objects on heap → sweep unmarked → (optional) compact
Mention stop-the-world pauses and that GC languages still leak via static caches, listeners, and unclosed resources.