Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET OutOfMemoryException

Why does this:

class OutOfMemoryTest02
{
    static void Main()
    {
        string value = new string('a', int.MaxValue);
    }
}

Throw the exception; but this wont:

class OutOfMemoryTest
{
    private static void Main()
    {
        Int64 i = 0;
        ArrayList l = new ArrayList();
        while (true)
        {
            l.Add(new String('c', 1024));

            i++;
        }
    }
}

Whats the difference?

like image 700
ksm Avatar asked Nov 22 '10 18:11

ksm


People also ask

What is OutOfMemoryException C#?

When data structures or data sets that reside in memory become so large that the common language runtime is unable to allocate enough contiguous memory for them, an OutOfMemoryException exception results.

What causes system OutOfMemoryException?

OutOfMemoryException Class (System) The exception that is thrown when there is not enough memory to continue the execution of a program.


1 Answers

Have you looked up int.MaxValue in the docs? it's the equivalent of 2GB, which is probably more RAM than you have available for a contiguous block of 'a' characters - that is what you are asking for here.

http://msdn.microsoft.com/en-us/library/system.int32.maxvalue.aspx

Your infinite loop will eventually cause the same exception (or a different one indirectly related to overuse of RAM), but it will take a while. Try increasing 1024 to 10 * 1024 * 1024 to reproduce the symptom faster in the loop case.

When I run with this larger string size, I get the exception in under 10 seconds after 68 loops (checking i).

like image 187
Steve Townsend Avatar answered Nov 14 '22 00:11

Steve Townsend