Reputation: 1903
Why is there a different for stack variables if we declare them in the global or function scope? One of the two example crashes, because of stack overflow. But only the one, which define a variable inside the scope.
Does crash:
constexpr size_t MAX = 1000000; // Customise
int main()
{
int arr[MAX];
return arr[MAX - 1];
}
Does not crash:
constexpr size_t MAX = 1000000; // Customise
int arr[MAX];
int main()
{
return arr[MAX - 1];
}
Info: Cygwin, GCC 4.9
Edit: So I know, the second example have is memory in the data segment. How big can the data segment be? Could it be so big as the heap area?
Upvotes: 0
Views: 119
Reputation: 903
The first one
constexpr size_t MAX = 1000000; // Customise
int main()
{
int arr[MAX];
return arr[MAX - 1];
}
You declare array in a function, so it goes to stack which is limited and will cause stack overflow.
The second one
constexpr size_t MAX = 1000000; // Customise
int arr[MAX];
int main()
{
return arr[MAX - 1];
}
You declare it at global, should be accesible between function so it goes to heap (rather big). So not using stack here.
Source : Static and global variable in memory
Upvotes: 2