0

I am trying to understand C# garbage collection and want to simulate a memory leak by using static root field. GC doesn't perform very well (which is good), however the objects are collected. In the example below, why does memory not leak? Should field Counter not prevent instances of MemLeakRoot class from being collected?

This is what is supposed to be a leaking class:

public class MemLeakRoot
{
    public static int Counter;

    public List<byte[]> MyList;

    public MemLeakRoot() { }

    public void Do()
    {
        MyList = new List<byte[]>();
        for (int i = 0; i < 10000; i++)
        {
            MyList.Add(new byte[1024]);
        } 

        Counter++;
    }
}

And this is the simulation:

static void Main(string[] args)
{
    while (true)
    {
        var obj = new MemLeakRoot();
        obj.Do();

        if (MemLeakRoot.Counter != 0 && MemLeakRoot.Counter % 1000 == 0)
        {
            Console.Write("+");
            if (MemLeakRoot.Counter % 100000 == 0) Console.WriteLine(MemLeakRoot.Counter.ToString());
        }
    }
}
Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
lekso
  • 1,731
  • 3
  • 24
  • 46
  • 2
    You always overwrite the `MyList` with a new instance and add new arrays to it, so the old `byte[]` are ready to be garbage collected. – Tim Schmelter Jul 11 '17 at 12:28
  • 1
    If the `byte[]` was another custom class you could force a memory leak by [subscribing to a static event](https://stackoverflow.com/a/6568033/284240). But apart from that the .NET garbage collector does it's job very good. – Tim Schmelter Jul 11 '17 at 12:41
  • _"Should field Counter not prevent instances of MemLeakRoot class from being collected?"_ -- no, it should not. Why do you think it should? GC happens on the basis of "reachability". An object that is not reachable, is eligible for GC. A static value type field has no way to make any of the objects you allocated reachable, so they are eligible for GC once the code is done with them. – Peter Duniho Jul 11 '17 at 21:09
  • thank you both for reply. If moderators want to delete this question then I don't mind – lekso Jul 17 '17 at 08:09

0 Answers0