Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I get OutOfMemoryException while trying to make an int array with size int.MaxValue

Tags:

arrays

c#

int

I am trying to make an array which holds all the positive integers possible, I tried the following code and it allways throws out of memory exception.

private int[] AllIntegers()
{
    int[] all = new int[int.MaxValue];

    for (int i = 0; i < int.MaxValue; i++)
    {
        all[i] = i;
    }

    return all;
}

What I am doing wrong? or this is not possible at all?!

like image 816
Saeid Yazdani Avatar asked Dec 13 '22 07:12

Saeid Yazdani


2 Answers

There's a hard upper limit on .NET object sizes, they cannot be larger than 2 gigabytes. Even on a 64-bit operating system. Your array is well beyond that size.

On a 32-bit operating system you'll never get close to that limit, the largest chunk of contiguous virtual memory available is around 650 megabytes, give or take. Only at startup, this goes down hill rapidly. This is a side effect of address space fragmentation, caused by having a mix of code and heaps in the address space. The total amount of memory you can allocate is close to 2 gigabytes, as long as the size of each allocation is small enough. Not something you'd ever want to get close to, random program failure due to OOM is hard to deal with.

like image 88
Hans Passant Avatar answered Dec 14 '22 20:12

Hans Passant


Int.MaxValue = 2,147,483,647, sizeof(int) = 4, so you would need 8 GB of memory to allocate this array. The exception indicates that your OS is not able to allocate this amount of memory.

== UPDATE ==

MSDN:

When you run a 64-bit managed application on a 64-bit Windows operating system, you can create an object of no more than 2 gigabytes (GB).

See also: BigArray<T>, getting around the 2GB array size limit

like image 34
kol Avatar answered Dec 14 '22 21:12

kol