Memory safe in D
Richard (Rikki) Andrew Cattermole
richard at cattermole.co.nz
Thu Mar 28 15:01:45 UTC 2024
On 28/03/2024 7:24 AM, Lance Bachmeier wrote:
> On Wednesday, 27 March 2024 at 17:07:57 UTC, Meta wrote:
>
>> I say this all as someone who would love to have a robust typestate
>> system for D, but it just ain't gonna happen. D is just not the
>> language for it. Your best bet is to either propose it for OpenD, or
>> fork it and implement it yourself.
>
> I'd say the best strategy would be to write up some examples using real
> code showing large benefits. Then it might have a chance. The current
> proposal not only assumes the reader is familiar with the concepts, but
> that they can envision substantial benefits in their own code. I had no
> more idea of the benefits after reading the proposal than I did before.
First example has been added, thanks to Razvan's recent Rust link:
However because it doesn't enable you to do anything new, and only ever
checks against certain logic errors it has been very difficult for me to
create examples it needs a different head space which I expected to deal
with later, oh well.
```d
T* makeNull(T)() @safe {
return null;
}
void useNull() @safe {
int* var = makeNull!int();
// var is in type state initialized as per makeNull return state
*var = 42;
// segfault due to var being null
}
```
What we want to happen instead:
```d
T* makeNull(T)(/* return'initialized */) @safe {
return null;
// type state default is more than the type state initialized
// so it is accepted
}
void useNull() @safe {
int* var = makeNull!int();
// var is in type state initialized as per MakeNull return state
// perform load via var variable
// this will error due to initialized is less than the nonnull type
state
// Error: Variable var is in type state initialized which could be
null, cannot write to it
*var = 42;
}
```
To fix, simply check for null!
```d
void useNull() @safe {
int* var = makeNull!int();
// var is in type state initialized as per MakeNull return state
if (var !is null) {
// in scope, assume var is in type state nonnull
*var = 42;
}
}
```
More information about the Digitalmars-d
mailing list