Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using a local clone.

Garbage Collection

D is a systems programming language with support for garbage collection. Usually it is not necessary to free memory explicitly. Just allocate as needed, and the garbage collector will periodically return all unused memory to the pool of available memory.

D also provides the mechanisms to write code where the garbage collector is not involved. More information is provided below.

C and C++ programmers accustomed to explicitly managing memory allocation and deallocation will likely be skeptical of the benefits and efficacy of garbage collection. Experience both with new projects written with garbage collection in mind, and converting existing projects to garbage collection shows that:

Garbage collection is not a panacea. There are some downsides:

These constraints are addressed by techniques outlined in Memory Management, including the mechanisms provided by D to control allocations outside the GC heap.

There is currently work in progress to make the runtime library free of GC heap allocations, to allow its use in scenarios where the use of GC infrastructure is not possible.

How Garbage Collection Works

The GC works by:

  1. Stopping all other threads than the thread currently trying to allocate GC memory.
  2. ‘Hijacking’ the current thread for GC work.
  3. Scanning all ‘root’ memory ranges for pointers into GC allocated memory.
  4. Recursively scanning all allocated memory pointed to by roots looking for more pointers into GC allocated memory.
  5. Freeing all GC allocated memory that has no active pointers to it and do not need destructors to run.
  6. Queueing all unreachable memory that needs destructors to run.
  7. Resuming all other threads.
  8. Running destructors for all queued memory.
  9. Freeing any remaining unreachable memory.
  10. Returning the current thread to whatever work it was doing.

Interfacing Garbage Collected Objects With Foreign Code

The garbage collector looks for roots in:

  1. the static data segment
  2. the stacks and register contents of each thread
  3. the TLS (thread-local storage) areas of each thread
  4. any roots added by core.memory.GC.addRoot() or core.memory.GC.addRange()

If the only pointer to an object is held outside of these areas, then the collector will miss it and free the memory.

To avoid this from happening, either

Pointers and the Garbage Collector

Pointers in D can be broadly divided into two categories: Those that point to garbage collected memory, and those that do not. Examples of the latter are pointers created by calls to C's malloc(), pointers received from C library routines, pointers to static data, pointers to objects on the stack, etc. For those pointers, anything that is legal in C can be done with them.

For garbage collected pointers and references, however, there are some restrictions. These restrictions are minor, but they are intended to enable the maximum flexibility in garbage collector design.

Undefined behavior:

Things that are reliable and can be done:

One can avoid using pointers anyway for most tasks. D provides features rendering most explicit pointer uses obsolete, such as reference objects, dynamic arrays, and garbage collection. Pointers are provided in order to interface successfully with C APIs and for some low level work.

Working with the Garbage Collector

Garbage collection doesn't solve every memory deallocation problem. For example, if a pointer to a large data structure is kept, the garbage collector cannot reclaim it, even if it is never referred to again. To eliminate this problem, it is good practice to set a reference or pointer to an object to null when no longer needed.

This advice applies only to static references or references embedded inside other objects. There is not much point for such stored on the stack to be nulled because new stack frames are initialized anyway.

Object Pinning and a Moving Garbage Collector

Although D does not currently use a moving garbage collector, by following the rules listed above one can be implemented. No special action is required to pin objects. A moving collector will only move objects for which there are no ambiguous references, and for which it can update those references. All other objects will be automatically pinned.

D Operations That Involve the Garbage Collector

Some sections of code may need to avoid using the garbage collector. The following constructs may allocate memory using the garbage collector:

Configuring the Garbage Collector

Since version 2.067, The garbage collector can now be configured through the command line, the environment or by options embedded into the executable.

By default, GC options can only be passed on the command line of the program to run, e.g.

app "--DRT-gcopt=profile:1 minPoolSize:16" arguments to app

Available GC options are:

In addition, --DRT-gcopt=help will show the list of options and their current settings.

Command line options starting with "--DRT-" are filtered out before calling main, so the program will not see them. They are still available via rt_args.

Configuration via the command line can be disabled by declaring a variable for the linker to pick up before using it's default from the runtime:

extern(C) __gshared bool rt_cmdline_enabled = false;

Likewise, declare a boolean rt_envvars_enabled to enable configuration via the environment variable DRT_GCOPT:

extern(C) __gshared bool rt_envvars_enabled = true;

Setting default configuration properties in the executable can be done by specifying an array of options named rt_options:

extern(C) __gshared string[] rt_options = [ "gcopt=initReserve:100 profile:1" ];

Evaluation order of options is rt_options, then environment variables, then command line arguments, i.e. if command line arguments are not disabled, they can override options specified through the environment or embedded in the executable.

References