Search code examples
c++arraysglobal-variablesprogram-entry-pointlocal-variables

Why on declaring an array global in c++, the size that it can be given is larger than declaring it in main


On declaring array as global i can give its size as 5000000 bt it is not possible when i declare it in main why?

works fine

#include<iostream>

int arr[5000000];
using namespace std;
int main()
{ 
  arr[0]=1;
  cout<<arr[0];
  return 0;
}

segmentation fault

#include<iostream>

using namespace std;
int main()
{
  int arr[5000000];
  arr[0]=1;
  cout<<arr[0];
  return 0;
}

Solution

  • In main the array is allocated on stack. The default limit for stack size is 8MB. The array is 20 MB, so stack overflow happens.

    The global array is allocated on data segment. The data segment size is by default unlimited as far as there is available memory.

    Run ulimit -a command in bash to see default limits for programs.