How a Garbage Collector Finds Memory to Reclaim

An application creates objects—such as strings, lists, and records—in memory as it runs. The difficult question is not whether an object looks old or unimportant, but whether the program can still reach it. A garbage collector answers that by tracing references: it starts from places the program is actively using, such as local variables and global data, then follows pointers from one object to another.

If an object cannot be reached from any of those starting points, the program has no reference through which to use it. The collector can treat its memory as available again. This is why an object that still exists in memory may be considered garbage, while an object the program will never need again may remain allocated if some lingering reference still points to it.

Reclaiming Space Has a Cost

A common approach is to mark every reachable object, then sweep through memory and reclaim what was not marked. Other collectors copy reachable objects into a new region, leaving the old region free all at once. Some also move objects to reduce fragmentation—the scattered gaps that can make it harder to fit new allocations into available memory.

That work takes processor time, and some collectors briefly pause application code while they inspect memory. Others do much of the work alongside the application, trading a more complex process for shorter interruptions. The design choice affects how quickly memory is reclaimed and how responsive the program feels.

“Unused” Means Unreachable

Garbage collection reduces the need for programmers to free every object by hand, but it cannot infer intent. If an application accidentally keeps a reference to an object it no longer needs, the collector must preserve it. The memory is technically reachable, even if it is useless to the application—a common source of memory leaks in garbage-collected programs.

So the collector’s real rule is precise: it reclaims what the program can no longer reach, not everything a person would call unnecessary. A forgotten reference can keep old data occupying space while active tasks compete for the memory.