Will this code cause a memory leak?
#include <stdexept> class MyClass { public: MyClass() { throw std::runtime_error("Test"); } }; int main() { try { MyClass * myClass = new MyClass; } catch (const std::exception & exc) { // Memory leak? } return 0; }
The memory allocated by new
is never deleted. Is this taken care of internally, or it an actual memory leak?
A constructor does not allocate memory for the class object its this pointer refers to, but may allocate storage for more objects than its class object refers to. If memory allocation is required for objects, constructors can explicitly call the new operator.
A memory leak occurs when you lose a pointer to allocated memory. Since you no longer know of its location, you aren't able to deallocate the memory.
Assignment (operator=) It will look similar to the copy constructor, but it will check for self assignment and then deallocate the old memory before allocating new memory.
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
The memory will be automatically freed before the exception propagates.
This is essential, because a) the program never receives a pointer to free, and b) even if it did, it would have no portable way to actually free it since the memory never became an object that you can delete.
The memory will be properly deallocated.
Related questions at SO.
prasoon@prasoon-desktop ~ $ cat noleak.cpp && g++ noleak.cpp && valgrind --leak-check=full ./a.out #include <stdexcept> class MyClass { public: MyClass() { throw std::runtime_error("Test"); } }; int main() { try { MyClass * myClass = new MyClass; } catch (const std::exception & exc) { // Memory leak? } return 0; } ==3652== Memcheck, a memory error detector ==3652== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==3652== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info ==3652== Command: ./a.out ==3652== ==3652== ==3652== HEAP SUMMARY: ==3652== in use at exit: 0 bytes in 0 blocks ==3652== total heap usage: 3 allocs, 3 frees, 106 bytes allocated ==3652== ==3652== All heap blocks were freed -- no leaks are possible ==3652== ==3652== For counts of detected and suppressed errors, rerun with: -v ==3652== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 17 from 6) prasoon@prasoon-desktop ~ $
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With