In C++ How to program there is a paragraph that say:
A common programming practice is to allocate dynamic memory, assign the address of that memory to a pointer, use the pointer to manipulate the memory and deallocate the memory with delete when the memory is no longer needed. If an exception occurs after successful memory allocation but before the delete statement executes, a memory leak could occur. The C++ standard provides class template unique_ptr in header to deal with this situation.
Any on could introduce me a real example that exception occur and memory will leak like this post?
If the call to
some_function_which_may_throw(p)
throws an exception we leak the memory pointed to byp
.A bit more subtle example.
Take an naive implementation of a class that holds two dynamically allocated arrays:
Now, if we get an exception because we call method
Bar
somewhere, everything's fine - the stack unwinding guarantess thatf
's destructor gets called.But if we get a
bad_alloc
when initializingsecond
, we leak the memory thatfirst
points to.To have a less contrived example, I recently found this potential leak in my code when allocating nodes with a given allocator object.
It's less obvious how to fix this because of the buffer, but with help I got it:
Compiling Code here
Simple example
See also: C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]