Sunday, May 15, 2011

The mechanics of function calls

Other day i was going thru the lectures of  Richard Buckland from UNSW. As he was explaining about the mechanism of function calls.
In actual , computer stores the data of the function (such as arguments, local variables, return address etc.,) when a function is invoked and destroys them when the function returns. Similarly when a function calls other functions, the caller function returns only after all the callee functions are returned.

It's a  last-in-first-out, meaning, it's a impelmeation as of stack .
In the memory, the stack grows from the higher memory address to the lower memory addresses. So we have to visualize an inverted stack.
Here's some keywords need to be remembered. It'll let you know what are they and explain little bit of them .
Here's they go.

Stack frame
The section of memory where the local variables, arguments, return address and other information of a function are stored, is called stack frame or activation record.

Stack pointer
For function calls, a bulk of data is pushed and popped from the memory, whenever a function is invoked and returned respectively. But we may need to access the data which is deep into the stack and it will be inefficient to pop off all the data to do that. Hence, unlike conventional stack implementation, we have a register called stack pointer that points to top of the stack such that all the addresses smaller than the address to which the stack pointer points are considered as garbage and all the address larger are considered as valid.

Stack bottom – It is the highest valid address of the stack. When the stack is initialized the stack pointer points to stack bottom.

Stack limit – It is the smallest valid address of the stack. When the stack pointer goes below this address, then there’s stack overflow.

Frame pointer – When a new function is invoked the frame pointer points to where the stack pointer was and when the function returns the stack pointer points back to where the frame pointer is.

Return address – It points to address (within the caller function) to which the control should pass when the callee (current) function returns.

Static link is for the nested functions. When a function (nested function) is defined within another function (enclosing function), the nested function may need to access the variables of the enclosing function. Therefore, the nested function’s stack frame should be able to access the enclosing function’s frame. This made possible by static link which points to the address of the enclosing function’s frame.

Try to understand below, diagram on the basis of above definations and corelate how the fucntion calls works.

I get a chance to get this some where so sharing the knowlege here.

No comments:

Post a Comment

Health Benefits of Cashews

  Benefits of Cashews. Healthy food is an integral part of healthy body. Regular exercises such as Yoga and healthy diet is important to...