Program crash: GC destroys an object unexpectedly

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Sep 21 20:47:41 UTC 2021


On Tue, Sep 21, 2021 at 08:36:49PM +0000, eugene via Digitalmars-d-learn wrote:
> On Tuesday, 21 September 2021 at 20:17:15 UTC, eugene wrote:
> 
> > Now, change operation order in the main like this:
> 
> Actually, all proposed 'fixes'
> 
> - use stopper somehow in the end (writeln(stopper.sg0.number))
> - change operation order
> - etc
> 
> are strange. I mean it's strange (for me) that these
> fixes make garbage collector behave as needed.

It's not strange.  You're seeing these problems because you failed to
inform the GC about the dependency between Main and stopper. So it's
free to assume that these are two independent, unrelated objects, and
therefore it can collect either one as soon as there are no more
references to it.

And since stopper isn't used anymore after declaration, an optimizing
compiler is free to assume that it's not needed afterwards, so it's not
obligated to keep the reference alive until the end of the function.

Since in actually there *is* a dependency between these objects, the
most "correct" solution is to include a reference to stopper somewhere
in Main. Then the GC would be guaranteed never to collect stopper before
Main becomes unreferenced.


T

-- 
Век живи - век учись. А дураком помрёшь.


More information about the Digitalmars-d-learn mailing list