Stack Unwinding in C++
Introduction
Stack Unwinding is the process of removing function entries from function call stack at run time. On this page we will discuss about the stack unwinding in C++.
About Stack Unwinding in C++
Stack unwinding in C++ refers to the process of unwinding the call stack, which is the memory structure that stores the return addresses of function calls.
This process occurs when an exception is thrown and propagates up the call stack, looking for a catch block that can handle the exception. As the stack unwinds, the destructors of local objects are called, and any memory allocated on the stack is freed. This process ensures that resources are properly released and memory is not leaked in the event of an exception.
Example of Stack Unwinding in C++
#include <iostream> #include <exception> using namespace std; class MyException:public exception { public: MyException():exception() {} const char *what() const throw() { return "My Exception"; } }; class MyResource { public: MyResource() { cout << "MyResource acquired" << endl; } ~MyResource() { cout << "MyResource released" << endl; } }; void function1() { MyResource res; throw MyException(); } void function2() { function1(); } void function3() { function2(); } int main() { try { function3(); } catch (const MyException& e) { cout << "Caught exception: " << e.what () << endl; } return 0; }
Output:
MyResource acquired MyResource released Caught exception: My Exception
This program defines a custom exception class MyException and a class MyResource that has a constructor that prints “MyResource acquired” and a destructor that prints “MyResource released” when it’s called.
In this example:
- The function3() calls function2() and function2() calls function1() and in function1() the class object is created and it throws a custom exception of type MyException.
- The exception propagates up the call stack, looking for a catch block that can handle it. In this case, the catch block is located in the main function.
- As the stack unwinds, the destructors of any local objects will be called in the reverse order of their construction.
As you can see in the output, first the resource is acquired, then the exception is thrown and goes up the call stack, and finally caught in the catch block, the destructor of the resource is called. This process of going up the call stack to find the catch block and calling the destructor of the objects is what is known as stack unwinding.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment