Accessing memory after destroy
Moritz Maxeiner via Digitalmars-d
digitalmars-d at puremagic.com
Sat Jul 29 15:15:41 PDT 2017
On Saturday, 29 July 2017 at 20:44:30 UTC, Johan Engelen wrote:
> [...]
> ```
> class Foo { int x; this() { x = 1; } }
> Foo foo = new Foo;
> destroy(foo);
> assert(foo.x == int.init); // object is still accessible
> ```
> [...]
> 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?
D's GC uses (conservative) stop-the-world mark-and-sweep, i.e. as
long as a memory chunk is reachable via a root it won't be
collected (see [1]). Since in your example the (stack) variable
`foo` is still referring to the (heap) memory location of the
destroyed object, if a garbage collection cycle is started
between `destroy(foo);` and `assert(foo.x == int.init);` by
another thread then - barring bugs - the memory location `foo`
refers to will be marked as alive and not collected.
[1] https://dlang.org/library/core/memory/gc.collect.html
More information about the Digitalmars-d
mailing list