Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

arrays

c

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?

like image 700
user1113314 Avatar asked Apr 08 '14 18:04

user1113314


People also ask

Why global array has a larger size than the local array?

When an array is declared globally then it stores in the data segment, and the data segment has no size limit. Hence, when the array is declared of big size (i.e., more than 107) then the stack memory gets full and leads into the stack overflow error, and therefore, a segmentation fault error is encountered.


1 Answers

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.

like image 172
Peter Gluck Avatar answered Oct 01 '22 03:10

Peter Gluck