GC doesn't collect where expected

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 19 18:22:55 UTC 2023


On 6/19/23 2:01 PM, axricard wrote:

> 
> Does it mean that if my function _func()_ is as following (say I don't 
> use clobber), I could keep a lot of memory for a very long time (until 
> the stack is fully erased by other function calls) ?
> 
> 
> ```
> void func()
> {
>     Foo[2048] x;
>     foreach(i; 0 .. 2048)
>       x[i] = new Foo;
> }
> ```
> 

When the GC stops all threads, each of them registers their *current* 
stack as the target to scan, so most likely not.

However, the compiler/optimizer is not trying to zero out stack 
unnecessarily, and likely this leads in some cases to false pointers. 
Like I said, even the "clobber" function might not actually zero out any 
stack because the compiler decides writing zeros to the stack that will 
never be read is a "dead store" and just omit that.

This question comes up somewhat frequently "why isn't the GC collecting 
the garbage I gave it!", and the answer is mostly "don't worry about 
it". There is no real good way to guarantee an interaction between the 
compiler, the optimizer, and the runtime to make sure something happens 
one way or another. The only thing you really should care about is if 
you have a reference to an item and it's prematurely collected. Then 
there is a bug. Other than that, just don't worry about it.

-Steve


More information about the Digitalmars-d-learn mailing list