Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory deallocation and exceptions

Tags:

c++

exception

I have a question regarding memory deallocation and exceptions. when I use delete to delete an object created on the heap . If an exception occurs before this delete is the memory going to leak or this delete is going to execute ?

like image 869
brett Avatar asked Aug 15 '10 07:08

brett


3 Answers

In the case you describe, memory is going to leak.

Two tricks to avoid this problem :

  • use smart pointers, which don't suffer from the same problem (preferred solution)
    --> the smart pointer in constructed on the stack, its destructor is therefore called, no matter what, and deletion of the pointed content is provided in the destructor

  • use try/catch statements, and delete the item in catch statement as well

like image 57
Benoît Avatar answered Oct 15 '22 00:10

Benoît


This depends on where that delete is. If it's inside the catch that catches the exception, it might invoke.

try {
    f();  // throws
} catch( ... ) {
    delete p;  // will delete
}

If it's after the catch that catches the exception and that catch doesn't return from the function (i.e. allows execution flow to proceed after the catch block) then the delete might be called.

try {
    f();  // throws
} catch( ... ) {
    // execution proceeds beyond catch
}
delete p;  // will delete

If the delete is not in a catch block or after a catch block that allows execution to proceed then the delete will not call.

try {
    f();  // throws
    delete p;  // will not delete
}  // ...

As you may imagine, in the two first cases above the delete will not be invoked if there is a throw before the delete:

try {
    f();  // throws
} catch( ... ) {
    g();  // throws
    delete p;  // will not delete
}
like image 4
wilhelmtell Avatar answered Oct 15 '22 02:10

wilhelmtell


It won't be called. Which is why you are encouraged to look at RAII. See Stroustrup

like image 2
dirkgently Avatar answered Oct 15 '22 02:10

dirkgently