views:

1022

answers:

3

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++?

+12  A: 

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. An even better solution would be to use std::vector<int> and resize it to 1000000 elements.

Charles Salvia
Thanks for the answer, but could you explain me why arrays are allocated on the stack and why not in the main program memory.
The given code allocates on the stack because it's specified as an array with a constant number of elements at compile time. Values are only put on the heap with malloc, new, etc.
Seth Johnson
All automatic varables are allocated on the stack. If you look at the disasseble you will see the size of your local variables subtracted from the stack pointer. When you call malloc or calloc or any of the memory fuctions the fuctions go and find blocks of memory large enough to sataisfy your reqest.
rerun
+1  A: 

You array is being allocated on the stack in this case attempt to allocate an array of the same size using alloc.

rerun
+3  A: 

In C or C++ local objects are usually allocated on the stack. You are allocating something large on the stack, more than the stack can handle, so you are getting a STACKOVERFLOW.

Don't allocate it local on stack, use some other place instead. This can be achived by making the object global. Global variables are fine, if you don't use the from any other compilation unit. To make sure, this doesn't happen by accident, add a static storage specifier.

This will allocate in the BSS segment, which is a part of the heap:

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

This will allocate in the DATA segment, which is a part of the heap too:

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

This will allocate somwhere unspecified in the heap:

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