How do I clear dynamic memory when an exception is thrown?

advertisements
void a(){
    int *ptr = new int(10);
    throw 1;        // throwing after memory allocation
    delete ptr;
}
int main(){
    try{
        a();
    } catch(...){
        cout << "Exception"<<endl;
    }
 }

this program will cause memory leak, is there a way to clear the dynamic memory allocated..?


In C++, you use the concept called RAII for that.

In short: Don't needlessly use dynamically allocated memory, so in your case

void a(){
    int i;
    throw 1;        // No dynamic allocation, no problem
}

without a new, and if you can't do that, have some scope based owner handle the lifetime:

void a(){
    auto ptr = std::make_unique<int>(10);
    throw 1;        // Allocation handled properly, no problem
}

This will automatically delete the int when it goes out of scope.

Rule of thumb: If your code has a delete or delete[] or a naked new or new[], you probably have a bug.