Garbage collection

kinke noone at nowhere.com
Sat Jun 27 14:12:09 UTC 2020


On Saturday, 27 June 2020 at 10:08:15 UTC, James Gray wrote:
> have run into a memory leak

Something seems really off indeed. I've run this on Win64 with 
DMD (2.092) and LDC (1.22), without any extra cmdline options:

-----
import core.memory;
import core.stdc.stdio;
import std.range;
import std.format;

auto f(R)(R r) { return format("%s", r); }

int toMB(ulong size) { return cast(int) (size / 1048576.0 + 0.5); 
}

void printGCStats()
{
     const stats = GC.stats;
     const used = toMB(stats.usedSize);
     const free = toMB(stats.freeSize);
     const total = toMB(stats.usedSize + stats.freeSize);
     printf("  GC stats: %dM used, %dM free, %dM total\n", used, 
free, total);
}

void main()
{
     printGCStats();

     while (true)
     {
         puts("Starting");
         string str = f(iota(100_000_000));
         printf("  string size: %dM\n", toMB(str.length));
         str = null;
         GC.collect();
         printGCStats();
     }
}
-----

Output with DMD (no change with the precise GC via 
`--DRT-gcopt=gc:precise`):
-----
   GC stats: 0M used, 1M free, 1M total
Starting
   string size: 943M
   GC stats: 1168M used, 1139M free, 2306M total
Starting
   string size: 943M
   GC stats: 1168M used, 2456M free, 3623M total
Starting
   string size: 943M
   GC stats: 1168M used, 2456M free, 3623M total
Starting
   string size: 943M
   GC stats: 1168M used, 2456M free, 3623M total
Starting
   string size: 943M
   GC stats: 1168M used, 2456M free, 3623M total
-----

With LDC:
-----
   GC stats: 0M used, 1M free, 1M total
Starting
   string size: 943M
   GC stats: 1168M used, 1139M free, 2306M total
Starting
   string size: 943M
   GC stats: 2335M used, 1288M free, 3623M total
Starting
   string size: 943M
   GC stats: 2335M used, 2605M free, 4940M total
Starting
   string size: 943M
   GC stats: 2335M used, 2605M free, 4940M total
Starting
   string size: 943M
   GC stats: 2335M used, 2605M free, 4940M total
-----

Note that I explicitly clear the `str` slice before GC.collect(), 
so that the stack shouldn't contain any refs to the fat string 
anymore.


More information about the Digitalmars-d-learn mailing list