Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When OutOfMemoryException occurs?

Consider this code:

string value = new string('a', int.MaxValue);

When we run that code OutOfMemoryException occurs.Physical memory limits in Windows 8 is 128 GB.

So why .Net throw OutOfMemoryException for that code?

Also this code never throw OutOfMemoryException :

List<string> list = new List<string>();
for (int i = 0; i < 100000000000; i++)
{
    list.Add(new string('a', 100 ));
}

I run it on 64 bit mode.


2 Answers

The maximum size for an object in .NET is 2 GB, even with gcAllowVeryLargeObjects enabled on 64 bits systems (the documentation on gcAllowVeryLargeObjects reads The maximum size for strings and other non-array objects is unchanged., I guess because of the way it was implemented).

That means you can only allocate a string with a size of 2GB. Since sizeof(char) is 2 and you have a little overhead in the class itself, the maximum size you can set is int.MaxValue / 2 - 32.

like image 78
Patrick Hofman Avatar answered May 12 '26 06:05

Patrick Hofman


You need 1 int.MaxValue * 2 of contiguous memory for your first example. Your 2nd example needs 100000000000 100 byte * 2 of contiguous memory.

.NET just can't find a single chunk big enough to fit it all into one space.

There also is a 2GB hard limit on object sizes. On 64 bit platforms you can make it larger with gcAllowVeryLargeObjects but that setting affects arrays only and will not affect the limit on strings.

like image 41
Scott Chamberlain Avatar answered May 12 '26 05:05

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!