@safe - why does this compile?

ketmar ketmar at ketmar.no-ip.org
Fri Jul 13 14:51:17 UTC 2018


Steven Schveighoffer wrote:

> To emphasize the point, this is @safe as well:
>
> X2 x2; // = null
> x2.run();
>
> D does not consider a segmentation fault due to null dereferencing to be 
> unsafe -- no memory corruption happens.

yeah. in simple words: safe code is *predictable*, but not "segfault-less". 
segfaults (null dereferences) in safe code are allowed, 'cause they have 
completely predictable behavior (instant program termination).

@safe doesn't free you from doing your null checks, it protects you from 
so-called "undefined behavior" (aka "unpredictable execution results"). so 
when we are talking about "memory safety", it doesn't mean that your code 
cannot segfault, it means that your code won't corrupt random memory due to 
misbehaving.


More information about the Digitalmars-d-learn mailing list