Memory safe in D

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Mon Mar 11 11:09:40 UTC 2024


On 12/03/2024 12:01 AM, Alex wrote:
> Yes, I got it about compiler, static analyzer can't detect such 
> potential issue for now.
> The instance of class `A` is initialized by default initializer - correct?.
> But what about variable `a`?

The instance of class ``A`` only exists as a reference stored in ``a``.

``a`` is null, therefore there is no instance of ``A``.

> Is it initialized by null or contains reference to the instance 
> initialized by default initializer?

The variable is a pointer, and it is null aka 0.

```d
void main() {
     Object o;
}
```

is

```asm
_Dmain:
		push	RBP
		mov	RBP,RSP
		sub	RSP,010h
		mov	qword ptr -8[RBP],0
		xor	EAX,EAX
		leave
		ret
```

No different if the type was ``int*`` instead of ``Object``.

```d
void main() {
     int* o;
}
```

```asm
_Dmain:
		push	RBP
		mov	RBP,RSP
		sub	RSP,010h
		mov	qword ptr -8[RBP],0
		xor	EAX,EAX
		leave
		ret
```

> What happend when I tried to call method `run()` of `a` in runtime?
> 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).
> Is it uncatched excpetion? But I have tried to catch it - not work.

A class reference is a pointer.

It basically works out to be something like this:

```d
struct Obj {}

void func(Obj* this) {}

Obj* obj;
func(obj);
```

If the function reads or writes to the this pointer, its going to segfault.

Same principle with the vtable lookup.

If you make your method on the class final, it should work the exact 
same way as the struct above, due to it not using the vtable.



More information about the Digitalmars-d mailing list