Jayesh
Jayesh

Reputation: 4903

What will happens if before freeing memory allocated by new operator, exception occurred?

I just curious to know, What will happens if before freeing memory allocated by new operator, exception occurred? Is it memory leak problem occurred?

#include <iostream>
#include<new>

using namespace std;

void func()
{
    try
    {
        int *p = new int[10];

        /*
            Number of lines code here
            .
            .
            .
            .
            .
            Suppose here I got exception then What heppens????
            .
            .
            .
            .
        */
        delete []p;
    }
    catch(const std::exception& e)
    {
        cout<<"Exception occured"<<endl;
    }
}

int main() {
    func();
    return 0;
}

Upvotes: 0

Views: 71

Answers (2)

Timmy_A
Timmy_A

Reputation: 1232

Memory leak occurs because operator delete has never been called. Use std::unique_ptr<T> instead of the raw C++ pointers. C++ standard library provides std::unique_ptr<T> that automatically de-allocates wrapped pointer when it's out of scope. C++ standard library also provides std::shared_ptr<T>, that uses reference counting and de-allocates memory only if the last reference to the pointer is released.

Upvotes: 2

Is it memory leak problem occurred?

Yes. This is the whole reason smart pointers and the whole RAII idiom were devised. Destructors of block scoped variable are still called when a handler is found, so those can free the allocated resources. A raw pointer will just leak.

Upvotes: 6

Related Questions