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?!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With