How to allocate/free memory under @nogc
Paul Backus
snarwin at gmail.com
Thu May 21 02:57:52 UTC 2020
On Thursday, 21 May 2020 at 02:50:22 UTC, data pulverizer wrote:
> I'm a bit puzzled about the whole `@nogc` thing. At first I
> thought it just switched off the garbage collector and that you
> had to allocate and free memory manually using `import
> core.memory: GC;` I tried this and it failed because @nogc
> means that the function can not allocate/free memory
> (https://dlang.org/spec/function.html#nogc-functions). If this
> is the case, how do you allocate/free memory without using the
> garbage collector? Does allocating and freeing memory using
> `GC.malloc` and `GC.free` avoid D's garbage collector? Also
> what is the syntax for removing dangling pointers?
Marking a function @nogc means you can't use the garbage
collector in that function, or call other functions that use it.
It's still there, and functions that are not marked @nogc can
still use it.
To allocate memory without the GC, you have a couple of options.
The simplest is to use C's malloc function, which can be found in
the core.stdc.stdlib module. A more complicated but more powerful
option is to use a non-GC-based memory allocator from the
std.experimental.allocator package. Either way, you will have to
take care of freeing the memory yourself, either manually or
using a technique like RAII.
More information about the Digitalmars-d-learn
mailing list