Enhancements can enable memory-safe reference counting

Paul Backus snarwin at gmail.com
Wed May 26 21:48:40 UTC 2021


On Wednesday, 26 May 2021 at 18:53:21 UTC, vitoroak wrote:
> Every time I tried to do something similar in D I stumbled 
> across the same problems and as far as I know it's not possible 
> to implement it completely @safe today. I think one of the 
> problems is that you can manually destroy/move any struct while 
> there are still references/pointers to it or its internals like 
> in the example below (I used your borrow mixin template).

In theory, these examples are fine, since they result in a null 
dereference, which is guaranteed by [the language spec][1] to be 
memory-safe (i.e., to immediately crash the program).

In practice, this is *usually* what will happen, but neither DMD, 
LDC, nor GDC actually *guarantees* an immediate crash upon null 
dereference in all cases. In particular, a null dereference with 
a large enough offset (e.g., a struct or class member access 
through a null pointer) can in principle cause memory corruption 
at runtime by accessing an address beyond the protected pages at 
the start of the address space.

You can work around this by adding an explicit null check:

     pure @safe
     ref Access access() return
     {
         // assert(0) is not compiled out in release mode
         if (_address !is null) assert(0);
         return *_address;
     }

[1]: https://dlang.org/spec/function.html#safe-values


More information about the Digitalmars-d mailing list