The "@safe vs struct destructor" dilemma

Michel Fortin michel.fortin at michelf.ca
Sat Apr 12 04:16:25 PDT 2014


On 2014-04-12 09:01:12 +0000, "deadalnix" <deadalnix at gmail.com> said:

> On Saturday, 12 April 2014 at 03:02:56 UTC, Michel Fortin wrote:
>> 2- after the destructor is run on an object, wipe out the memory block 
>> with zeros. This way if another to-be-destructed object has a pointer 
>> to it, at worse it'll dereference a null pointer. With this you might 
>> get a sporadic crash when it happens, but that's better than memory 
>> corruption. You only need to do this when allocated on the GC heap, and 
>> only pointers need to be zeroed, and only if another object being 
>> destroyed is still pointing to this object, and perhaps only do it for 
>> @safe destructors.
> 
> You don't get a crash, you get undefined behavior. That is much worse 
> and certainly not @safe.

You get a null dereference. Because the GC will not free memory for 
objects in a given collection cycle until they're all destroyed, any 
reference to them will still be "valid" while the other object is being 
destroyed. In other word, if one of them was destroyed and it contained 
a pointer it'll be null. That null dereference is going to be like any 
other potential null dereference in @safe code: it is expected to crash.

There's still the problem of leaking a reference somewhere where it 
survives beyond the current collection cycle. My proposed solution 
doesn't work for that. :-(

-- 
Michel Fortin
michel.fortin at michelf.ca
http://michelf.ca



More information about the Digitalmars-d mailing list