14

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?

0

1 Answer 1

24

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Also don't forget to check that malloc succeeded
In Visual Studio, you could probably use this to increase the stack maximum size: msdn.microsoft.com/en-us/library/tdkhxaks.aspx
While the whole thing -- where goes what -- about globals and objects with explicit static duration is an implementation detail, typically uninitialized variables go to .bss section and don't inflate binary size. And using namespace std; is frowned upon in C++.
I'm not sure if I got it right. If the array is stored on the HDD - wouldn't the operations on the array be super slow? And if it's stored in the RAM - then where if it's neither in the stack nor the heap?
During execution a statically initialized array is loaded into RAM and operated on in RAM. There is more to memory than heap and stack. For more info, see the tutorial referenced in the answer.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.