Accessing memory after destroy

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Sat Jul 29 16:09:38 PDT 2017


On Saturday, July 29, 2017 20:44:30 Johan Engelen via Digitalmars-d wrote:
> I'd like to check a bit of info I need for Address Sanitizer
> checking.
>
> The spec says [1]:
> Use the destroy function to finalize an object by calling its
> destructor. The memory of the object is not immediately
> deallocated, instead the GC will collect the memory of the object
> at an undetermined point after finalization:
> ```
>    class Foo { int x; this() { x = 1; } }
>    Foo foo = new Foo;
>    destroy(foo);
>    assert(foo.x == int.init);  // object is still accessible
> ```
>
> This tells me 2 things that I'd like to verify:
> 1. The destroyed memory is set to the type's `.init` value. (but
> the Ctor is not called)
> 2. It is _valid_ to access the memory after calling destroy.
>
> Point 2 is worrying: what if there is a thread switch right after
> destroy, in which a GC collect happens?
>
> Thanks,
>    Johan
>
> [1] https://dlang.org/spec/class.html#deallocators

If destroy has been called on a class object, then it is a bug to access it
at any point after that (IIRC, the expectation is that it will blow up in
your face, because the vtable is gone - TDPL talks about this, I believe,
but I don't know where my copy is at the moment, so I can't check). That
being said, the memory is still valid. And as Moritz pointed out, if the
memory is accessible, the GC won't free it. So, it's a bug to access the
object, but it should be memory safe to do so.

- Jonathan M Davis



More information about the Digitalmars-d mailing list