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.