Hot interview questions: 02 – Stack Unwinding

Categories: Programming

Stack unwinding is strictly related to exceptions. Let’s consider the following example:


float div ( int dividend, int divisor );   // assuming just int!
int main()
{
try
{
float quotient = div( 10, 0 );
std::cout << "result = " << quotient << std::endl;
}
catch (const std::exception& e)
{
return 1;
}
return 0;
}

float div ( int dividend, int divisor )
{
char* myStr = new char[512];   // 2^9 = 512Byte allocated on heap!
std::string s("Division by zero!");
if (divisor == 0)
throw std::runtime_error(s);
delete []myStr;   //be careful here ... memory leak in case of exception!!!
}

in this example, in the div method, we see that when the divisor is zero an exception is raised. Different things happen here:

  1. In the div’s caller once the exception is cached the destructor of every (automatic) object (i.e.: allocated on the stack) is called. Known as: Stack unwinding. The object are destroyed in the reverse order of their construction.
  2. in case of divisor equal to zero an exception is raised and myStr is not deallocated, while the string’s destructor is correctly called! One GOOD reason to use the STL as much as possible … otherwise you’re just pretending to write C++ code!
  3. what would happen in the “stack unwinding phase” in case a destructor raise an exception itself? well first: it shouldn’t[1]. Indeed you cannot use your class (with a destructor that can raise an exception) with the standard containers (std::vector, std::list, etc)! second: the terminate() method is called and your application will be terminated 🙁 … the rules is: If during stack unwinding a destructor throws an exception and that exception is not handled (one reason is that another exception is already under evaluation for example), the terminate() function is called.

 

[1] Exceptional C++ Sutter: “No destructor operation defined in the C++ Standard Library will throw an exception.” Not only do all the standard classes have this property, but in particular it is not permitted to instantiate a standard container witha type whose destructor does throw


    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.