How compiler manages runtime stack?

390 Views Asked by At

There are lots of questions asked about stack & heap on this site. But i want to know about how compiler manages stack actually? Is the stack based allocation is decided at runtime or compile time? Consider following example:

#include <iostream>
using namespace std;
class Test {
 // Test class' data members
 public:
 // member functions
};
int main() {
  Test t; // automatic object
  // use t here
  return 0;
}

The question here is when object t will be allocated? memory will be allocated at compile time or runtime? I know that local variables, objects gets allocated when function is called & destroyed when function terminates.

3

There are 3 best solutions below

0
On BEST ANSWER

Stack based allocation is decided at compile time and is executed at run time. When the compiler "sees" the declaration of Test t, it generates code to allocate sizeof(Test) bytes on the stack for t and optionally to call its ctor. When the function exits, the compiler generates code to call the dtor (if it exists) and to deallocate the space.

However, C99 introduced variable length arrays. They are also allocated on the stack, but their size if determined at run time. See this.

Hope this answers your question.

0
On

The Compiler takes the decision to have the runtime allocate on the stack.

0
On

It mostly depends on the system actually. a compiler can estimate how much memory it needs to allocate when compiling.

However, mostly it is done at runtime because stack use is difficult to estimate because it is code dependent, and can vary between runs depending on the code path that the program takes on execution