GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing dlang.org — Automatic Memory Management - D Programming Language Language Reference
Report a bug
If you spot a problem with this page, click here to create a GitHub 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.
Automatic Memory Management Contents
D is a systems programming language with support for optional automatic memory mangagement. Usually it is not necessary to free memory explicitly. Just allocate as needed, and the automatic memory manager's collector will periodically return all unused memory to the pool of available memory. D also provides the mechanisms to write code where automatic memory mangagement is not involved. More information is provided below. Programmers accustomed to explicitly managing memory allocation and deallocation will likely be skeptical of the benefits and efficacy of automatic memory management. Experience both with new projects written with automatic memory management in mind, and converting existing projects to automatic memory management shows that:
Automatic memory management 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 collector heap. There is currently work in progress to make the runtime library free of automatic heap allocations, to allow its use in scenarios where the use of automatic memory management infrastructure is not possible. How Automatic Memory Management WorksIt works by:
Interfacing Automatic Memory Management Allocated Objects With Foreign CodeThe collector looks for roots in:
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 Automatic Memory Management CollectorPointers in D can be broadly divided into two categories: Those that point to collector 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 collector pointers and references, however, there are some restrictions. These restrictions are minor, but they are intended to enable the maximum flexibility in 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 automatic memory management. Pointers are provided in order to interface successfully with C APIs and for some low level work. Working with the CollectorAutomatic memory allocation doesn't solve every memory deallocation problem. For example, if a pointer to a large data structure is kept, the 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 CollectorAlthough D does not currently use a moving 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 CollectorSome sections of code may need to avoid using the collector. The following constructs may allocate memory using the collector:
There is a @nogc function attribute which will error at compile-time if any construct is used which would make a collector allocation. Configuring the CollectorSince version 2.067, The 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 its 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. Precise Heap ScanningSelecting precise as the collector via the options above means type information will be used to identify actual or possible pointers or references within heap allocated data objects. Non-pointer data will not be interpreted as a reference to other memory as a "false pointer". The collector has to make pessimistic assumptions if a memory slot can contain both a pointer or an integer value, it will still be scanned (e.g. in a union). To use the collector memory functions from core.memory for data with a mixture of pointers and non-pointer data, pass the TypeInfo of the allocated struct, class, or type as the optional parameter. The default null is interpreted as memory that might contain pointers everywhere. struct S { size_t hash; Data* data; } S* s = cast(S*)GC.malloc(S.sizeof, 0, typeid(S)); Attention: Enabling precise scanning needs slightly more caution with type declarations. For example, when reserving a buffer as part of a struct and later emplacing an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using void* is usually the best option as it also ensures proper alignment for pointers being scanned by the GC. Precise Scanning of the DATA and TLS segmentWindows only: As of version 2.075, the DATA (global shared data) and TLS segment (thread local data) of an executable or DLL can be configured to be scanned precisely by the garbage collector instead of conservatively. This takes advantage of information emitted by the compiler to identify possible mutable pointers inside these segments. Immutable pointers with initializers are excluded from scanning, too, as they can only point to preallocated memory. Precise scanning can be enabled with the D runtime option "scanDataSeg". Possible option values are "conservative" (default) and "precise". As with the collector options, it can be specified on the command line, in the environment or embedded into the executable, e.g. extern(C) __gshared string[] rt_options = [ "scanDataSeg=precise" ]; Attention: Enabling precise scanning needs slightly more caution typing global memory. For example, to pre-allocate memory in the DATA/TLS segment and later emplace an object instance with references to other allocations into this memory, do not use basic integer types to reserve the space. Doing so will cause the garbage collector not to detect the references. Instead, use an array type that will scan this area conservatively. Using void* is usually the best option as it also ensures proper alignment for pointers being scanned by the GC. class Singleton { void[] mem; } align(__traits(classInstanceAlignment, Singleton)) void*[(__traits(classInstanceSize, Singleton) - 1) / (void*).sizeof + 1] singleton_store; static this() { emplace!Singleton(singleton_store).mem = allocateMem(); } Singleton singleton() { return cast(Singleton)singleton_store.ptr; }For precise typing of that area, let the compiler generate the class instance into the DATA segment: class Singleton { void[] mem; } shared(Singleton) singleton = new Singleton; shared static this() { singleton.mem = allocateSharedMem(); }This doesn't work for TLS memory, though. See also: void arrays. Parallel markingBy default the collector uses all available CPU cores to mark the heap. This might affect your application if it has threads that are not suspended during the mark phase of the collection. Configure the number of additional threads used for marking by collector option parallel, e.g. by passing --DRT-gcopt=parallel:2 on the command line or embedding the option into the binary via rt_options. The number of threads actually created is limited to core.cpuid.threadsPerCPU-1. A value of 0 disables parallel marking completely. Adding your own CollectorCollector implementations are added to a registry that allows to supply more implementations by just linking them into the binary. To do so add a function that is executed before the D runtime initialization using pragma(crt_constructor): import core.gc.gcinterface, core.gc.registry; extern (C) pragma(crt_constructor) void registerMyGC() { registerGCFactory("mygc", &createMyGC); } GC createMyGC() { __gshared instance = new MyGC; instance.initialize(); return instance; } class MyGC : GC { /*...*/ } [The collector modules defining the interface (gc.interface) and registration (gc.registry) are currently not public and are subject to change from version to version. Add an import search path to the druntime/src path to compile the example.] The new collector is added to the list of available collectors that can be selected via the usual configuration options, e.g. by embedding rt_options into the binary: extern (C) __gshared string[] rt_options = ["gcopt=gc:mygc"]; The standard GC implementation from a statically linked binary can be removed by redefining the function extern(C) void* register_default_gcs(). If no custom garbage collector has been registered all attempts to allocate collector managed memory will terminate the application with an appropriate message. References
Copyright © 1999-2026 by the D Language Foundation | Page generated by
Ddoc on Mon Nov 9 05:59:20 2026
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |