Reputation: 48
I created this simple C# program expecting it to throw OutOfMemoryException. Problem is it works perfectly without using all my laptop memory. Why? How can I make it leak all the memory?
static void Main(string[] args)
{
for (int i = 0; true; i++)
{
new MustDispose();
}
}
class MustDispose
{
public MustDispose()
{
StreamReader r = null;
r = File.OpenText("C:\\Users\\rverdelli\\Desktop\\asd.txt");
if (r.EndOfStream) return;
Console.WriteLine(r.ReadToEnd());
}
}
Upvotes: 0
Views: 221
Reputation: 59605
In your method MustDispose()
, there is one character which is important:
}
This defines the end of a scope, which means that local variables are no longer valid. Being no longer valid tells the garbage collector to remove the local variables, particularly r
as well as all temporary results which haven't even been assigned to a variable (i.e. the boolean return value of r.EndOfStream
and the string r.ReadToEnd()
).
There are various possibility to eat all memory, e.g.
var keeper = new List<byte[]>();
while(true)
{
keeper.Add(new byte[1024*1024]);
}
If the IDisposable interface is implemented correctly, the Finalizer will check if Dispose() has already been called. If not, the Finalizer will do so.
Upvotes: 3
Reputation: 203825
Each iteration of your loop isn't storing any state beyond the scope of that iteration, so when it's over all of the memory allocated in that iteration can be freed.
If you want to run out of memory you'll need to hold onto the memory that you're allocating.
Here's a simple enough example that shouldn't have a problem running you out of memory:
var data = Enumerable.Range(0, int.MaxValue)
.Select(i => new int[int.MaxValue])
.ToArray();
Console.WriteLine(data.Length);
Upvotes: 3