Stack Unwinding in C++


Here we will see what is the meaning of stack unwinding. When we call some functions, it stores the address into call stack, and after coming back from the functions, pops out the address to start the work where it was left of.

The stack unwinding is a process where the function call stack entries are removed at runtime. To remove stack elements, we can use exceptions. If an exception is thrown from the inner function, then all of the entries of the stack is removed, and return to the main invoker function.

Let us see the effect of stack unwinding through an example.

Example Code

#include <iostream>
using namespace std;

void function1() throw (int) { //this function throws exception
   cout<<"\n Entering into function 1";
   throw 100;
   cout<<"\n Exiting function 1";
}

void function2() throw (int) { //This function calls function 1
   cout<<"\n Entering into function 2";
   function1();
   cout<<"\n Exiting function 2";
}

void function3() { //function to call function2, and handle
   exception thrown by function1
   cout<<"\n Entering function 3 ";
   try {
      function2(); //try to execute function 2
   }
   catch(int i) {
      cout<<"\n Caught Exception: "<<i;
   }
   cout<<"\n Exiting function 3";
}

int main() {
   function3();
   return 0;
}

Output

Entering function 3
Entering into function 2
Entering into function 1
Caught Exception: 100
Exiting function 3

Here we can see that the control stores info of function3, then enters into function2, and then into function1. After that one exception occurs, so it removes all of the information from stack, and returns back to function3 again.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements