Memory safe in D

Walter Bright newshound2 at digitalmars.com
Wed Mar 13 06:05:35 UTC 2024


On 3/12/2024 12:33 PM, Alex wrote:
> I think it depends on what we means "memory safety". If only "dangling 
> pointers", I agree.

Memory safety is not something we've uniquely defined. It's generally accepted 
that it specifically means no memory corruption. "Safe" programs can offer 
additional guarantees, like no race conditions.


> But if we want to have strict guarantee at compilation time 
> that any accessible reference leads to alive object answer is no, SafeD can't 
> provide such guarantee yet.

In general, we cannot guarantee that assert()'s won't trip at runtime, nor 
buffer overflow exceptions. All we can do is say we stop the program when it 
happens.

Actual memory corruption is infinitely worse than promptly stopping the program 
when it detects an internal bug.


>> It is always better to catch null mistakes at compile time rather than 
>> runtime, but it isn't a memory safety issue.
> 
> Are D foundation considering the possibility to implement something like this in 
> future version of D?

Consider the following:
```
class A { void bar(); }

void foo(int i) {
     A a;
     if (i) a = new A();
     ...
     if (i) a.bar();
}
```
What happens if we apply data flow analysis to determine the state of `a` when 
it calls `bar()`? It will determine that `a` has the possible values (`null`, 
new A()`). Hence, it will give an error that `a` is possibly null at that point.

Yet the code is correct, not buggy.

Yes, the compiler could figure out that `i` is the same, but the conditions can 
be more complex such that the compiler cannot figure it out (the halting problem).

So that doesn't work.

We could lower `a.bar()` to `NullCheck(a).bar()` which throws an exception if 
`a` is null. But what have we gained there? Nothing. The program still aborts 
with an exception, just like if the hardware checked. Except we've got this 
manual check that costs extra code and CPU time.

BTW, doing data flow analysis is very expensive in terms of compiler run time. 
The optimizer does it, but running the optimizer is optional for that reason.



More information about the Digitalmars-d mailing list