2

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;
}
Ankit Raonka
  • 6,429
  • 10
  • 35
  • 54

2 Answers2

4

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

3

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.

Hrant
  • 496
  • 1
  • 5
  • 13