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.
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.