Memory safe in D
Nick Treleaven
nick at geany.org
Sat Mar 30 09:38:52 UTC 2024
On Saturday, 30 March 2024 at 09:24:12 UTC, Nick Treleaven wrote:
> On Saturday, 30 March 2024 at 03:00:32 UTC, Walter Bright wrote:
>> On 3/22/2024 3:51 AM, Nick Treleaven wrote:
>>> I think this is workable without DFA, the compiler just
>>> tracks when a variable is initialized. There is never a state
>>> where a variable may be both initialized and not initialized
>>
>> ```
>> A a = null;
>> if (i)
>> a = new A();
>> // a is both initialized and not initialized
>> ```
>
> There `a` is always initialized. It's a nullable type. If you
> remove the `= null` and make `a` a non-nullable type, you would
> get an error for the `if` statement because it initializes `a`
> in its branch, and there is no `else` branch which is required
> to also initialize `a`.
This is an example for Herb Sutter's cppfront, which enforces
that `p` is non-null:
```c++2
main: () =
{
i := 0;
p: unique_ptr<int>;
if (i) {
p = new<int>; // error: p must be initialized on both
branches or neither
}
}
```
>> Now throw in loops and goto's, and DFA is needed. Compiler
>> optimizers use DFA because it works and ad-hoc techniques do
>> not.
cppfront:
```c++2
main: () =
{
i := 0;
p: unique_ptr<int>;
while i < 3 next i++ {
p = new<int>;
std::cout << p* << "\n"; // ok, p is always initialized
}
}
```
Changing the while loop:
```c++2
while i < 3 next i++ {
std::cout << p* << "\n"; // error, p used before it was
initialized
p = new<int>;
}
```
Goto skipping initialization is already disallowed in D.
> This does not need DFA, correct?
More information about the Digitalmars-d
mailing list