Q:

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;
}

A:

Take a look at this image of a program anatomy. In your second implementation, the memory is allocated on the stack, which according to the picture, has a limit of 8MB (different machine might have different limit). Your array will occupy about 20MB of memory. The data segment is larger than 8MB and therefore, no errors are thrown when trying to allocate such array

A:

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.

