Exceptions, stack unwinding, encapsulated heap memory, exit()

634 views Asked by At

When an exception is thrown, then the block where it is thrown is unwinded from stack:

int main ()
{
    try
    {
        Object x; // doesn't throw
        Object y; // throws
        cout << "wonderful";
    }
    catch (...)
    {
        cout << "fail";
    }
}

When Object allocates on construction memory on heap and deallocates it properly on destruction, then there should be no memory leak, because stack unwinding calls destructor of x (not of y, but Object guarantees, that when constructor failing, then no memory leak). As far all right, isn't it?

Let's go into depth:

int main ()
{
    Object x; // doesn't throw
    double *d = new double[256*256*256]; // doesn't throw
    Object y; // throws
    cout << "wonderful";
    delete[] d;
}

Because of good education, I want to clean my trash up by myself, and not let do it the OS. I know, that every modern OS deletes by itself heap memory of a program which terminates unexpected (or expected, but no explicit deallocation). So in the upper case, the deallocation of d would do my OS, but x would be still properly deallocating its memory (because of stack unwinding and destructor call) before OS would do it, right?

What about that:

#include <cstdlib>

int main ()
{
    Object x; // doesn't throw
    try { Object y; } // throws
    catch (...) {  cout << "fail"; exit(EXIT_FAILURE); }
    cout << "working and working...";
    cin.get();
}

Is the destructor of x called before exit gives control back to OS?

And more in depth:

void Object::be_stupid ()
{
    Object a; // doesn't throw
    try { Object b; }// throws
    catch (...) { exit(EXIT_FAILURE); }
}

void main ()
{
    Object x; // doesn't throw
    try { x.be_stupid(); } // exits program
}

Is the constructor of x called before exit gives control back to OS? If yes, then exit "unwinds" all surrounding stacks including main(), right?

1

There are 1 answers

0
mb84 On BEST ANSWER

Ok, got it thanks to polkadotcadaver: never use exit(), propagate exceptions until main() and do there a simple return - all stack Objects will be deallocated by their own destructor before OS takes control.