C - Function Call Mechanism and Call Stack in C
Function Call Mechanism – Definition
The function call mechanism describes how control and data are transferred from a calling function to a called function and how control returns after execution.
In C, this process is managed internally using the call stack.
Steps in Function Call Mechanism
1. Function Call
-
The calling function calls another function by name.
-
Actual parameters (arguments) are passed to the function.
Example:
sum(10, 20);
2. Parameter Passing
-
Arguments are copied into formal parameters.
-
C uses call by value by default.
Example:
void sum(int a, int b)
3. Stack Frame (Activation Record) Creation
A stack frame is created for the called function containing:
-
Function parameters
-
Local variables
-
Return address
-
Saved registers
4. Control Transfer
-
Control jumps from the calling function to the called function.
-
Execution starts from the first statement of the called function.
5. Function Execution
-
The function executes its statements using its local stack frame.
6. Return to Calling Function
-
The return value (if any) is passed back.
-
Stack frame of the called function is destroyed.
-
Control resumes from the next statement after the function call.
Call Stack – Definition
The call stack is a stack data structure used by C programs to:
-
Store information about active function calls
-
Manage nested and recursive function calls
It follows the LIFO (Last In, First Out) principle.
Structure of Call Stack
Each function call creates a stack frame containing:
-
Function arguments
-
Local variables
-
Return address
-
Temporary data
Example of Call Stack Working
Program:
void fun2() {
int b = 20;
}
void fun1() {
int a = 10;
fun2();
}
int main() {
fun1();
return 0;
}
Call Stack Execution Order:
-
main()stack frame created -
fun1()stack frame pushed -
fun2()stack frame pushed -
fun2()completes → popped -
fun1()completes → popped -
main()completes → popped
Call Stack in Recursion
-
Each recursive call creates a new stack frame
-
Excessive recursion can cause stack overflow
Example:
int fact(int n) {
if(n == 0)
return 1;
return n * fact(n - 1);
}
Importance of Call Stack
-
Manages function execution order
-
Stores local variables safely
-
Enables recursion
-
Ensures correct return of control
Advantages
-
Automatic memory management for local variables
-
Efficient function call handling
-
Supports nested and recursive calls
Limitations
-
Limited stack size
-
Stack overflow due to deep recursion
-
Local variables exist only during function execution