Reputation: 43
My goal is to reach a point where I have filled up all available memory (note that I want to do this incrementally, so before my last allocation I have a minimal memory remaining). How can I do this?
Upvotes: 4
Views: 1964
Reputation: 4992
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;
}
}
Upvotes: 2
Reputation: 59101
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
Upvotes: 1
Reputation: 43
int size = 1024;
var bytes = new List<byte[]>();
while (true)
{
try
{
bytes.Add(new byte[size]);
}
catch
{
if (size == 1)
{
throw;
}
size = size / 2;
}
}
Upvotes: 0
Reputation: 10764
Keep adding a large buffer to a memory stream inside a while loop .
Upvotes: 0
Reputation: 78252
Maybe something like this?
var bytes = new List<byte[]>();
var time = new TimeSpan(100);
while (true)
{
bytes.Add(new byte[1024]);
Thread.Sleep(time);
}
Upvotes: 0
Reputation: 60008
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.
Upvotes: 4