My goal is to reach a point where I have filled up all avalible memory (note that I want to do this incrementaly, so before my last alocation I have a minimal memory remaining). How can I do this?
One option would be to create a list of some kind, and just keep adding junk to it in an infinite loop.
Depending on the precision needed, though, that could take a while - one option for speeding it up would be adding large structs to the list elements initially, then catching the OutOfMemoryError and trying again with smaller stuff until you've got the precision you need.
Maybe something like this?
var bytes = new List<byte[]>();
var time = new TimeSpan(100);
while (true)
{
bytes.Add(new byte[1024]);
Thread.Sleep(time);
}
Keep adding a large buffer to a memory stream inside a while loop .
int size = 1024;
var bytes = new List<byte[]>();
while (true)
{
try
{
bytes.Add(new byte[size]);
}
catch
{
if (size == 1)
{
throw;
}
size = size / 2;
}
}
The scenario you are talking about sounds like it might be for testing an application.
You may want to look into load/stress testing tools. LoadRunner is the first one that comes to mind. It's not "in C#", and I am pretty sure it isn't free, but it may be the right tool for the job. Also, you may want to look into fault injection, if you all you want to see is how your program handles an OutOfMemory exception.
For exactly what you asked about, here's an article with an application that consumes RAM: http://msdn.microsoft.com/en-us/magazine/cc163613.aspx
var junk = new LinkedList<byte[]>();
int allocSize = 100 * 1024 * 1024; // 100 MiB
while (allocSize > 0)
{
try
{
junk.AddLast(null);
junk.Last.Value = new byte[allocSize];
}
catch (OutOfMemoryException)
{
allocSize = (allocSize - 1) / 2;
}
}