Gurpreet Singh
Gurpreet Singh

Reputation: 1376

Increasing the size of array creates some problem

I tried to check, what is the largest size of array, which can be created in CPP. I declared a "int" array and kept increasing the array size. After 10^9 the program started crashing, but there was a serious error for array of size 5*10^8 and more(even when program did not crash). The code used and the problem is following :

#include<iostream>
int ar[500000000];
int main()
{
    printf("Here\n");
}

The above code runs successfully, if the size of array is reduced to 4*10^8 and lesser. But, for array size greater than 5*10^8, the program runs successfully but it does not print any thing, also it does not get crashed, or gave any error or warning.

Also, if the array definition is local then there is no such error, after same limit the program gets crashed. It's when using the global definition of array, the program does not get crashed nor does print anything.

Can anybody please explain the reason for this behavior. I've understood that the size of array will vary for different machines.

I've 1.2 GB of free RAM. How am I able to create the local integer array of size 4*10^8. This requires around 1.49GB, and I don't have that much free RAM.

Upvotes: 0

Views: 442

Answers (2)

dchhetri
dchhetri

Reputation: 7136

The real question is: why are you using globals? And to make it worse, it's a static raw array?

As suggested already, the memory used to hold global variables is being overflowed (and it possibly wrote over your "Here\n" string).

If you really need that big of an array, use dynamically-allocated memory:

int main() {
   int* bigArray = new int[500000000];
   // ... use bigArray here
   delete[] bigArray;
}

Upvotes: 2

Vijay Sharma
Vijay Sharma

Reputation: 373

C++ inherently doesn't restrict the max limits on the array size. In this case since it is a global variable it will be outside the stack as well. The only thing I can think of is the memory limit on your machine. How much memory does your machine has? How much memory is free before running your program?

Upvotes: 0

Related Questions