Viatorus February 2016

Declare variable in global/function scope. Stack difference?

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?

Answers


AchmadJP February 2016

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

Post Status

Asked in February 2016
Viewed 2,407 times
Voted 4
Answered 1 times

Search




Leave an answer