Radha Gogia
Radha Gogia

Reputation: 795

How is the amount of memory in stack area determined at compile time only?

Activation records are created in stack. These are created and destroyed during program run- that is stack area changes its size during program run.

Even though memory in stack area is created during run time- the amount of memory (activation record size) is determined at compile time.

I am not getting this concept that when memory in stack area is created during run time then how can the size of activation record determined at compile time ?

Upvotes: 2

Views: 701

Answers (1)

When the OS starts a process it allocates a fixed amount of space for that process t use as a stack. Memory is not created or destroyed when functions start or end. It is borrowed from the top of the whatever is unused on the stack.

When a function is called it grabs a chuck of that stack space ( at the top of stack ) that it will use itself ( for variable ). The compiler can scan a function and calculate all that in advance, as it does not need to allow for function calls made with each function - they are all treated independently.

As a function exists it releases that stack space ( simply adjusts the stack pointer back to what it was ) and returns to the caller.

As every function called does it's own reserve and free of space from the top of stack, the compiler does not need to allow for stack space used by functions called within other functions. Each function always works from the existing top of the stack ( where the free space is ).

Malloc() uses the heap memory, which is separate from the stack. Only local variables use the stack. There is an unsafe function called alloca() that also uses the stack, but it is not normally used as it cannot be relied on to return a valid pointer.

Upvotes: 2

Related Questions