A huge amount of memory leakage in a C++ project which was from a mistaken 'new' statement which was not deleted

  • 0
    I would expect that the memory gets released when the variable goes out of scope again - can you sum up the pitfall that you encountered?
  • 4
    @jtag been there, done that, lol. In my case the program ran out of memory in like half a second. Also, considering your name, were you working on embedded systems?

    @Fast-Nop not after a new, that's heap allocated. It's like C's malloc with slightly different internal machinery. You need to free the memory manually or stuff it in a memory management object, like a smart pointer.
  • 0
    @RememberMe yeah I know that new allocates on the heap, but that should be freed automatically - I'd expect the destructor to do that? Or is delete mandatory?
  • 5
    @Fast-Nop the destructor is called when you delete the memory manually via a delete operator. As in,

    auto ptr = new Class();
    delete ptr; // only (standard) way to call the destructor.

    The general way to solve this is to make a stack allocated container, like a std::unique_ptr, and stuff the pointer returned by new into it. When the unique_ptr goes out of scope, its destructor will trigger the destructor of the thing you put inside it.
  • 1
    @RememberMe I see, thanks!
Add Comment