Dynamic array leak?

Yuxuan Shui via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 11 12:01:44 PDT 2017


On Friday, 11 August 2017 at 18:44:56 UTC, bitwise wrote:
> struct S {
>     static int count = 0;
>     this(int x) { ++count; }
>     this(this) { ++count; }
>     ~this() { --count; }
> }
>
> int main(string[] argv)
> {
>     S[] x = [S(1), S(1)];
>     writeln("GC allocated: ", (GC.addrOf(x.ptr) !is null));
>     x = null;
>     GC.collect();
>     writeln("live objects: ", S.count);
>     return 0;
> }
>
> output:
> GC allocated: true
> live objects: 2
>
> expected:
> GC allocated: true
> live objects: 0
>
> Is this a bug?
>
> I thought that the first writeln() may be leaving a copy of the 
> pointer lingering on the stack somewhere, but the output is 
> still "live objects: 2" with that line commented out.
>
>   Thanks

My guess is a pointer to the array still lives somewhere on the 
stack. This gives the expected output:

void f()
{
     S[] x = [S(1), S(1)];
     writeln("GC allocated: ", (GC.addrOf(x.ptr) !is null));
     x = null;
}

int main(string[] argv)
{
     f();
     GC.collect();
     writeln("live objects: ", S.count);
     return 0;
}


More information about the Digitalmars-d mailing list