Young
Young

Reputation: 25

Will below code cause memory leak?

I want to create a memory leak by using C#, so I write the following code try to create one. The concept is to write a explicit Dispose which do nothing but call GC.SuppressFinalize() to prevent the GC's work. But it seams like the memory doesn't leak when I was running the code. Can anyone help to tell me why?

class Program
{
    static void Main(string[] args)
    {
        while (true)
        {
            var t = new Foo();
            t.create_leak();
            t.Dispose();
        }
    }        
}
class Foo:IDisposable
{
    public void create_leak() {
        m_value = new int[10000];
        Console.WriteLine(m_value[10].ToString()+DateTime.Now.ToString());
    }

    public void Dispose() { GC.SuppressFinalize(this); }

    private int[] m_value;

    ~Foo() { }
}

Upvotes: 1

Views: 410

Answers (3)

Tomasz Polecki
Tomasz Polecki

Reputation: 306

I suggest you use objects like "Bitmaps" or "Fonts" to generate the memory leak. These objects requires you to explicitly dispose it as otherwise could cause a memory leak. An example can be found here:

Continuous creation of bitmaps leads to memory leak

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062650

That isn't a leak, because each Foo is still eligible for collection at the end of each loop; the SuppressFinalize just means that ~Foo() will not be called - it doesn't change the fact that each m_value is eligible for collection.

It is pretty hard to get a genuine leak. If you just want to fill memory, keep all the Foo instances in a List<T> or similar - then they will never be eligible for collection. For a genuine leak, you might want to allocate unmanaged memory - perhaps Marshal.AllocHGlobal.

Upvotes: 3

Konrad Rudolph
Konrad Rudolph

Reputation: 545568

The concept is to write a explicit Dispose which do nothing but call GC.SuppressFinalize() to prevent the GC's work.

GC.SuppressFinalize doesn’t prevent the GC’s work. It merely prevents the GC from calling the finalizer on your object. But managed memory is still going to be reclaimed. If you want to create a memory leak, then you need to allocate unmanaged memory or allocate managed memory in such a fashion that it cannot be reclaimed (because it remains referenced indefinitely). String interning is one such way. Compiled regular expressions is another (however, that memory will of course still be reclaimed once your process terminates).

Upvotes: 3

Related Questions