If the compiler calculates the size of the stack required before runtime, how does a stack overflow occur? At compile time does the compiler calculate the total amount of memory required for stack of the whole program?
If the compiler calculates the size of the stack required before runtime, how does a stack overflow occur? At compile time does the compiler calculate the total amount of memory required for stack of the whole program?
No.
A compiler can only know what happens during runtime to some very limited extend. For example it cannot tell how much stack is needed to execute the following function:
void foo() {
int x = 0;
std::cin >> x;
if (x == 42) foo();
}
Stack is a limited resource and if you exceed it you get an stackoverflow.
Consider this very simplified example function (pseudocode)
void Foobar(long nested) {
if( --nested >= 0)
Foobar(nested);
}
Each call pushes (at least) the return address onto the stack.
Question: How much memory do you need for this?
Exactly. That's the reason.
The compiler will often know how much stack memory each function will require, but cannot know at compile time which functions are getting called. So you might get a stack of function calls that exceed the stack memory.
Also, stack memory can be changed between processes or threads, so the compiler don't know the limit at compile time.
Lastly, you can dynamically allocate memory on the stack. This is done through recursion or with calls like alloca in C.