Memory safe in D

Nick Treleaven nick at geany.org
Mon Mar 11 10:48:52 UTC 2024


On Monday, 11 March 2024 at 08:16:13 UTC, Alex wrote:
> Hello,
>
> I am interesting D as memory safe language (maybe SafeD?) and 
> have written very simple code:
>
> ```d
> @safe
>
> import std.stdio;

The `@safe` attribute there does nothing, it only applies to the 
import declaration, and is ignored. Perhaps you meant `@safe:` 
with the trailing colon, so it applies the attribute to every 
declaration after it in the module.

> So I don't see any errors or warnings from compiler when I use 
> uninitialized variable `a`

`a` is not uninitialized - you have to use `= void` for that 
(https://dlang.org/spec/declaration.html#void_init). 
Uninitialized pointers/references are not allowed in @safe 
functions.

> and don't see any exception with backtrace in runtime 
> (application is build in debug mode).

Try using optimization. On Linux, the backend can detect the null 
dereference at compile-time:
```
$ dmd -O os/nullobj.d
os/nullobj.d(22): Error: null dereference in function _Dmain
```
Line 22:
	a.run();

However, only simple cases are detected at compile-time.

> Is it expected behavior?
> Looks like it is not very safe approach and can lead to very 
> unpleasant memory errors...

@safe only means memory-safety:
https://dlang.org/spec/memory-safe-d.html

Null-safety is not part of memory-safety, because in D it should 
not be possible to violate memory-safety when a pointer/reference 
is null.

For a long time I've wanted compile-time null-safety using 
non-nullable pointers/references, but there are no plans to add 
that AFAIK.


More information about the Digitalmars-d mailing list