Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the stack memory allocated at runtime or compile time?

Tags:

c

stack-memory

Is the stack allocated at runtime or compile time?
Example:

void main()
{
    int x;
    scanf("%d", &x);
    int arr[x];
}
like image 396
user1426767 Avatar asked May 30 '12 18:05

user1426767


2 Answers

Stack is allocated at runtime; layout of each stack frame, however, is decided at compile time, except for variable-size arrays.

like image 195
Sergey Kalinichenko Avatar answered Sep 23 '22 15:09

Sergey Kalinichenko


It must be allocated at run time. Consider the following:

void a( void )
{
    int x;
}

void b( void )
{
    int y;
    a();
}

int main( void )
{
    a();
    b();
}

The address of the stack-local x in a() will be different between its two invocations. As blinkenlights points out, the layout of each function's stack frame is largely determined at compile time, but the placement of that frame is determined at run time.

like image 34
Russell Borogove Avatar answered Sep 22 '22 15:09

Russell Borogove