Question

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

void main()
{
    int x;
    scanf("%d", &x);
    int arr[x];
}
Était-ce utile?

La solution

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

Autres conseils

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.

how would you allocate compile time? if I compile the code on my machine but execute it on yours how would the compiler be able to preallocate the memory for the stack on your machine?

This should help. Stack memory is allocated at runtime.

Keep in mind that it has to be allocated at runtime, as there is no way for the compiler to know how many times a function is called, or how many times a while loop is executed, or whatever.

Stack is always allocated at runtime, you need stack for method execution not for compilation.

On Similar Lines

To complement all the other answers (which are correct in the general case), it is sometimes possible, in theory, to allocate stack at compile-time (depending on your definition of "allocate").

Specifically, if your program has no function pointers or recursion, then one can use static analysis to figure out the maximum stack size required. Indeed, some embedded compilers do precisely that.

Ofcourse stack is allocated at run time. You need stack memory for executing the code.ec

Check this link which discusses the memory layout of a C program.

Check out this great article

http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory

This is a great write up which explains about the program memory. You can also check other articles by the same author regarding memory behavior in s system which will give you a great insight into the actual working in memory.

if you want to know everything about memory try reading this paper by Ulrich Draper http://www.akkadia.org/drepper/cpumemory.pdf

hope this helps!

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top