16

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?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
user1113314
  • 803
  • 1
  • 10
  • 24

1 Answers1

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.

Peter Gluck
  • 8,168
  • 1
  • 38
  • 37
  • 1
    Also don't forget to check that malloc succeeded – dkrikun Apr 08 '14 at 19:06
  • 1
    In Visual Studio, you could probably use this to increase the stack maximum size: http://msdn.microsoft.com/en-us/library/tdkhxaks.aspx – dkrikun Apr 08 '14 at 19:08
  • 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++](http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – P.P Apr 08 '14 at 19:11
  • 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? – user1113314 Apr 08 '14 at 20:01
  • 2
    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. – Peter Gluck Apr 08 '14 at 20:31
  • Keep in mind that different OSs have different stack sizes, on Windows it seems to be 8 times smaller than on Linux (8MB vs 1MB) – simplegamer Mar 26 '19 at 20:25