Memory safe in D

ShowMeTheWay ShowMeTheWay at gmail.com
Fri Apr 12 10:21:19 UTC 2024


On Tuesday, 12 March 2024 at 03:55:27 UTC, Walter Bright wrote:
> On 3/11/2024 4:01 AM, Alex wrote:
>> Yes, I got it about compiler, static analyzer can't detect 
>> such potential issue for now.
>
> It cannot do it in the general case, that would be the halting 
> problem.
>
>> The instance of class `A` is initialized by default 
>> initializer - correct?.
>
> `A a;` will default initialize `a` to `null`.
>
> `A a = new A();` will allocate an instance of `A` where each 
> field is default initialized, and assign the result to `a`.
>
>> But what about variable `a`?
>
> `a` is default initialized to `null`.
>
>> Is it initialized by null or contains reference to the 
>> instance initialized by default initializer?
>
> `null`
>
>> What happend when I tried to call method `run()` of `a` in 
>> runtime?
>
> `a` is passed as the `this` pointer to the method `run()`. 
> Hence, in this case, `this` will be null. If you attempt to 
> dereference `this`, it will seg fault.
>
>> I see that application was abnormal termination because 
>> `writeln("Hello, world!");` was not called.
>> But I don't see any information in console about it (backtrace 
>> or something else).
>
> To get a backtrace on Windows, run it in the VC debugger.
>
>> Is it uncatched excpetion? But I have tried to catch it - not 
>> work.
>
> D's exception catchers do not catch Windows system exceptions 
> for 64 bit code. Microsoft has not seen fit to document their 
> 64 bit EH system.

The problem here, is "the D compiler" - i.e it not warning you 
(as an compilation error), that you are using variable a, even 
though it has not yet been assigned.

Unlike the D compiler, the C# compiler *would* tell you as much.

But D compiler just leaves it to the hardware to generate a seg 
fault at runtime??

This can be solved at compilation time.. surely.

C# ...
------
A a;
a.run(); // C# -> error CS0165: Use of unassigned local variable 
'a'
-----

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0165




More information about the Digitalmars-d mailing list