Memory safe in D

ShowMeTheWay ShowMeTheWay at gmail.com
Tue Apr 16 07:25:21 UTC 2024


On Monday, 11 March 2024 at 19:43:33 UTC, Steven Schveighoffer 
wrote:
> On Monday, 11 March 2024 at 08:16:13 UTC, Alex wrote:
>
>> Is it expected behavior?
>> Looks like it is not very safe approach and can lead to very 
>> unpleasant memory errors...
>
> So I know there are a lot of responses here, with a lot of 
> discussion. But I don't think anyone has told you *why* D works 
> this way.
>
> The explanation is that D is expecting the memory hardware to 
> fault when you dereference null. We know that this is not the 
> case for all situations, but it is the case for all of D's 
> normal usage modes (e.g. as user-code on standard operating 
> systems).
>
> Since the memory hardware *already supports this*, and is 
> essentially free, D has deferred to that mechanism to guard 
> against dereferencing null pointers. Not assuming this behavior 
> means all dereferences of pointers/classes in `@safe` code 
> would have to be instrumented with a check, slowing down the 
> code significantly.
>
> I consider null pointer faults to be annoying, but not nearly 
> as bad as dangling pointer accesses. At least a null pointer 
> *always* crashes when you access it.
>
> -Steve

The problem is less that the code is dereferencing null, and 
more, that "..forgetting to assign a value to a local is probably 
a bug.", to qoute Eric Lippert.

When you're derefencing null in a situation where you almost 
certainly should NOT be doing that, then it should be considered 
a likely bug.

To quote him some more,... "If its probably a bug and it is cheap 
and easy to detect, then there is good incentive to make the 
behavior either illegal or a warning."

Many of us use compilers (that have been around for decades), 
that do just that.

This below is valid C++ code, a bug in C#, but valid code in D 
(even though it's actually a bug):

A a;
a.run();

This should not be legal D code. It should produce an error if 
compiled.

It's not difficult for a compiler to work this one out.



More information about the Digitalmars-d mailing list