meJustAndrew meJustAndrew - 4 months ago 17
C# Question

Override finalize method to get a memory leak

I am curious, could be the code in this question used to get a memory leak, if we override the finalize method for both classes to re instantiate A and B filds in each class?

public class A
{
B b;
public A(B b) { this.b = b; }
~A()
{
b = new B();
}
}

public class B
{
A a;
public B() { this.a = new A(this); }
~B()
{
a = new A();
}
}


Now producing objects of A and B will result in some memory leaks, wouldn't it?

Answer

I finally managed to test a bit and I found what could be named a memory leak in C#, overriding the Finalize method. Here is a sample of code:

public class A
{
    B b;
    public A(B b) { this.b = b; }
    ~A()
    {
        b = new B();
    }
}

public class B
{
    A a;
    public B() { this.a = new A(this); }
    ~B()
    {
        a = new A(this);
    }
}

class Program
{
    static void Main(string[] args)
    {
        {
            B[] toBeLost = new B[100000000];
            foreach (var c in toBeLost)
            {
                toBeLost.ToString(); //to make JIT compiler run the instantiation above
            }
        }
        Console.ReadLine();
    }
}