Memory safe in D

Alex akornilov.82 at mail.ru
Mon Mar 11 13:16:04 UTC 2024


On Monday, 11 March 2024 at 10:48:52 UTC, Nick Treleaven wrote:
> 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.
Yes, I mean whole file declared as safe. Thank you!
I not so familiar with D yet :)

> `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.
Ok, got it, in my example variable is initialized by default 
value (null).

> 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
> ```
Thanks, it works on Windows to :)
Is it possible pass the compilation flag -O via `dub run`?

> Line 22:
> 	a.run();
>
> However, only simple cases are detected at compile-time.

You right, after this trivial modification compiler fails to 
detect bug :(

```d
     void doRun(A a) {
     	a.run();
     }

     int main()
     {
     	A a;
     	//a.run();
     	doRun(a);
     	writeln("Hello, world!");
     	return 0;
     }

```

> @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.

Formally yes, but segfault looks not good for language which say 
"I have memory safe feature", in my opinion. For example, Rust 
guarantees what successfully compiled code couldn't lead to 
crash/segfault.

> 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.

Very good idea! Hope you can implement it sooner or later :)



More information about the Digitalmars-d mailing list