...

/

The Garbage Collector

The Garbage Collector

You will learn about the working of the garbage collector in D in this lesson.

Garbage collection cycle

The dynamic variables that are used in D programs live on memory blocks that are owned by the garbage collector (GC). When the lifetime of a variable ends (i.e., it’s no longer being used), that variable is subject to being finalized according to an algorithm that is executed by the GC. If nothing else needs the memory location containing the variable, the memory may be reclaimed to be used for other variables. This algorithm is called garbage collection, and an execution of the algorithm is called a garbage collection cycle.

The algorithm that the GC executes can roughly be described by the following steps. All of the memory blocks that can be reached directly or indirectly by pointers (including references) that are in the program roots are scanned. Any memory block that can be ...