Size of 32bit max .net byte array <2gb?

I've been looking at some SO questions related to the maximum size of a byte array ( here and here ) and have been playing around with some arrays and getting some results that I don't quite understand. My code looks like this:

byte[] myByteArr;
byte[] myByteArr2 = new byte[671084476];

for (int i = 1; i < 2; i++)
{
    myByteArr = new byte[671084476];
}

      

This will compile and after executing it, it will generate 'System.OutOfMemoryException'

on initialization myByteArr

. If I change 2 in the for loop to 1, or I comment out one of the initializations (either myByteArr2

, or myByteArr

) it works fine.

It also byte[] myByteArr = new byte[Int32.MaxValue - 56];

throws the same exception.

Why does this happen when compiling to 32-bit? Aren't they within 2gb?

+3


source share


1 answer


The limits of a 32-bit program do not apply to every object. This is the process limit. You cannot use more than 2 GB.

Not only that, but in practice it is often difficult to get around 2GB due to the fragmentation of the address space. .NET managed (i.e. movable) memory helps somewhat, but does not fix the problem.



Even if you are using a 64-bit process, you may have a similar problem because in C # arrays is indexed int

, which is defined as a 32-bit signed integer and thus cannot access the past 2GB boundary in the byte array. If you read the answer to the second link carefully, you will also see that there is a 2GB limit per object. Presumably your byte array has some overhead, so it can't get the full 2GB just for the raw data.

See @Habib link in comments for details.

+3


source







All Articles