Segmentation fault on large array sizes

Mayank picture Mayank · Dec 4, 2009 · Viewed 105.2k times · Source

The following code gives me a segmentation fault when run on a 2Gb machine, but works on a 4GB machine.

int main()
{
   int c[1000000];
   cout << "done\n";
   return 0;
}

The size of the array is just 4Mb. Is there a limit on the size of an array that can be used in c++?

Answer

Charles Salvia picture Charles Salvia · Dec 4, 2009

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.