views:

182

answers:

3

Hi, I would like to write the following code in c#. a) small console application that simulates memory leak. b) small console application that would invoke the above application and release it right away simulating managing memory leak problem..

In other words the (b) application would continuously call and release application (a) to simulate how the "rebellious" memory leak application is being contained with out addressing the root cause which is application (a).

Some sample code for application (a) and (b) would be very helpful.

Thanks

+1  A: 

You can simulate a memory leak by simply adding objects to a global list on a timer.

Joel Coehoorn
A: 

Just Create IDisposable objects and don't dispose them! Examples being Image Graphics or any kind of handle or code that branches out into unmanaged code to create/manage resources.

Aren
IDisposable doesn't do anything special here. Any object will work, as long as you don't let it become unreachable.
Joey
+1  A: 

The leaking application might look like:

public static void Main()
{
  var list = new List<byte[]>();
  while (true)
  {
    list.Add(new byte[1024]); // Change the size here.
    Thread.Sleep(100); // Change the wait time here.
  }
}

And the calling application might look like:

public static void Main()
{
  Process process = Process.Start("leaker.exe");
  process.Kill();
}

Take a look at the properties on the Process class. There are several that return how much memory the process is consuming. You may be able to use one of them to conditionally kill the process.

Brian Gideon
I implemented your sample code. My Leaker.exe starts off with 6MB memory usage per task manager process tab. I don't know which property I could use to measure it... I get several properties any where from NonpagedSystemMemorySize all the way to VirtualMemorySize64 but I do not know which property would correspond to Task Manager memory usage. I tried to print memory property values to console but still no luck. Please help.
dotnet-practitioner
Have the leaker consume memory more aggresively by creating a bigger `byte` array. Try using `PrivateMemorySize64`. It should start creeping up over time.
Brian Gideon