Example of memory leak in c++ (by use of exceptions) -


in c++ how program there paragraph say:

a common programming practice allocate dynamic memory, assign address of memory pointer, use pointer manipulate memory , deallocate memory delete when memory no longer needed. if exception occurs after successful memory allocation before delete statement executes, memory leak occur. c++ standard provides class template unique_ptr in header deal situation.

any on introduce me real example exception occur , memory leak like post?

class myclass { public:     char* buffer;     myclass(bool throwexception)     {         buffer = new char[1024];         if(throwexception)             throw std::runtime_error("myclass::myclass() failed");     }      ~myclass()     {         delete[] buffer;     } }; 

int main() {     // memory leak, if exception thrown before delete     myclass* ptr = new myclass(false);     throw std::runtime_error("<any error>");     delete ptr; } 

int main() {     // memory leak due missing call myclass()::~myclass()     // in case myclass()::myclass() throws exception.     myclass instance = myclass(true); } 

see also: c++ : handle resources if constructors may throw exceptions (reference faq 17.4]


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -