Why does a large local array crash my program, but a global one doesn't? [duplicate]

Program with large global array:

int ar[2000000];

int main()
{
}

Program with large local array:

int main()
{
    int ar[2000000];
}

When I declare an array with large size in the main function, the program crashes with "SIGSEGV (Segmentation fault)".

However, when I declare it as global, everything works fine. Why is that?


Declaring the array globally causes the compiler to include the space for the array in the data section of the compiled binary. In this case you have increased the binary size by 8 MB (2000000 * 4 bytes per int). However, this does mean that the memory is available at all times and does not need to be allocated on the stack or heap.

EDIT: @Blue Moon rightly points out that an uninitialized array will most likely be allocated in the bss data segment and may, in fact, take up no additional disk space. An initialized array will be allocated statically.

When you declare an array that large in your program you have probably exceeded the stack size of the program (and ironically caused a stack overflow).

A better way to allocate a large array dynamically is to use a pointer and allocate the memory on the heap like this:

using namespace std;
int main() {
  int *ar;
  ar = malloc(2000000 * sizeof(int));

  if (ar != null) {
    // Do something 
    free(ar);
  }

  return 0;
}

A good tutorial on the Memory Layout of C Programs can be found here.