Memory safe in D

Alex akornilov.82 at mail.ru
Wed Mar 13 20:34:42 UTC 2024


On Wednesday, 13 March 2024 at 19:58:24 UTC, Steven Schveighoffer 
wrote:
> Then "optional" types, basically the same thing. Null is a 
> memory safe "invalid thing".
>
> The thing I'm getting at is -- if you have something that 
> doesn't exist, but is supposed to exist, then you have to deal 
> with it. How you deal with it is where the tradeoffs come in.
>
> The basic building block that all memory-safe language tools 
> are built on is -- you should not be able to use invalid 
> memory. null pointers which halt the program are a flavor of 
> that.

I think fundamental difference between optional type and nullable 
reference is that optional type is under control of compiler as 
type system of the language. But nullable refrence will "shoot" 
only in runtime and compiler can't help.

> Building non-null into the type indeed means as long as you 
> have that type, you don't have to check. But to get it into 
> that type, if you started with a possibly-invalid value, 
> *somewhere* you had to do a check.

Or have done initialization of variable by a new instance (good 
practice in contrast with variables without explicitly 
initialization).

> Consider an array/vector of items in Rust. And an index. When 
> you index that vector, the compiler has no idea what that index 
> is. It must validate the index before dereferencing the 
> element. This is a check, and the handling of it is defined by 
> the language.

Looks like the array boundary checks is not possible at 
compilation time at all. But null references might be handled by 
compiler thanks to type system.

> Having a possibly-null pointer is no different. D defines that 
> in safe code, a pointer will be valid or null. The "check" 
> occurs on use, and is performed by the hardware.

But the fundamental difference that null pointer checks is 
performed in D at runtime but in Kotlin (and other languages 
which support null safety) at compilation time.



More information about the Digitalmars-d mailing list