Open In App

Stack Frame in Computer Organization

Stack Frame :
Stack is one of the segments of application memory that is used to store the local variables, function calls of the function. Whenever there is a function call in our program the memory to the local variables and other function calls or subroutines get stored in the stack frame. Each function gets its own stack frame in the stack segment of the application’s memory. 

Features :



Structure of stack frame :
Stack pointer always points to the top and frame pointer stores address of whole stack frame of the subroutine. Each stack frame of a subroutine or a function contains as follows. 

Stack Frame
Other function calls
Other saved registers 
Local variables
Saved [Frame Pointer]
Of called function
Saved [Link Register]
Of called function
Passed arguments 
Frame pointer (F.P)

                                                                 A typical stack frame of a subroutine.



Implementation in C++ :
Let us consider an example program for better understanding the stack frame.




#include <iostream>
using namespace std;
  
//product method
int findProduct(int a, int b)
{
    int product = a * b;
    return product;
}
  
//findSum method
int findSum(int a, int b)
{
    int sum = a + b;
    return sum;
}
  
//main function
int main()
{
    int a = 6;
    int b = 6;
      
    //findProduct method called
    int product = findProduct(a, b);
      
    //findSum method called
    int sum = findSum(a, b);
    cout << "Product is :" << product << endl;
    cout << "Sum is :" << sum << endl;
  
    return 0;
}

Output :

Product is :36
Sum is :12

Explanation using Stack :

Step-1 :
When main() calls findProduct function a new stack frame is created as follows.

findProduct()

 a = 6 
 b=6

product = a* b

 
 
 main()
  a = 6             
  b=6
product = call to findProduct()
sum = call to findSum()

                                                                                  Stack 

Step-2 :
After function findProduct finishes its instruction and returns to main() and the stack frame for findProduct gets popped from stack. After that main() calls findSum() function.

findSum()
a = 6  
b=6
sum = a+ b
 
 

  main() 

    a = 6  
    b=6
   product = 36 
  sum = call to findSum()

                                                                                    Stack

Step-3 :
After function findSum finishes its instruction and returns to main() the findSum() gets popped from the stack as follows.

  main()
   a = 6  
   b=6   
  product = 36 
  sum = 12

                                                                                      Stack

Step-4 :
Now main() function executes the remaining statements and gets popped from the stack and the stack gets empty..


Article Tags :