SafeD doesn't prevent me from dereferencing a null reference

Tejas notrealemail at gmail.com
Thu Aug 18 15:27:17 UTC 2022


On Thursday, 18 August 2022 at 14:23:40 UTC, Yutori wrote:
> ```d
> void main(immutable string[] argv) @safe @live {
>         class Test {
>                 string a;
>         }
>         auto testInstance = new Test;
>         testInstance.a = "Test String";
>         import std.stdio;
>         testInstance.a.writeln;
>         testInstance = null;
>         testInstance.a.writeln;
> }
> /* Terminal output:
>         Test String
>         Segmentation fault
> */
> ```
> Of course, this code must spit out a segmentation fault, as 
> dereferencing null is illegal. However, the problem is, that it 
> lets me compile the program in @safe.
> I'm not entirely sure about what testInstance is defined as, 
> but I assume it's a reference. I don't think dereferencing null 
> should be allowed in SafeD. Or is this a design decision of D?

I believe this is a design decision, since you're not invoking UB 
in `@safe` code. Dereferencing a `null` pointer is assumed to 
crash your program, so it's allowed to be done in `@safe` code as 
well, since the semantics are deterministic.


More information about the Digitalmars-d mailing list