Reputation: 143
Is the stack allocated at runtime or compile time?
Example:
void main()
{
int x;
scanf("%d", &x);
int arr[x];
}
Upvotes: 14
Views: 10603
Reputation: 3576
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!
Upvotes: 0
Reputation: 272457
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.
Upvotes: 2
Reputation: 24895
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.
Upvotes: 0
Reputation: 19037
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.
Upvotes: 4
Reputation: 8818
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.
Upvotes: 2
Reputation: 21742
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?
Upvotes: 2
Reputation: 726479
Stack is allocated at runtime; layout of each stack frame, however, is decided at compile time, except for variable-size arrays.
Upvotes: 12
Reputation: 20323
Stack is always allocated at runtime, you need stack for method execution not for compilation.
Upvotes: 1