Lesson learned: if you're going to derive a class in c++, make sure to declare a virtual destructor on the base class!

I just fixed (one of...) the massive memory leaks in my damn project.

Pictured: the strings in a derived class actually getting freed!

  • 11
    I also learned about taking heap snapshots and how to read them. Cool stuff!
  • 3
    @AlgoRythm oh you remind me of yet another reason to never touch C++ again.
    Too many traps.
  • 4
    yeah i remember that was one of these gotchas with destructors in C++
  • 5
    just checking that you're using valgrind to investigate this and will never ever stop using it in the future
  • 3
    the worst part about this is that the compiler won't give a shit about it, even if it can directly detect this.

    Edit: clang-tidy has a warning for that, might be interesting (https://clang.llvm.org/extra/...)
  • 0
    @Hazarth I’m using smart pointers, lots of shared ownership too, will it work well in this case?
  • 3
    @Hazarth valgrind is super useful in general 👌
    but definitely a must have for C++
  • 1
    @AlgoRythm the word is, it's as smart as a smart phone. pick your poison
  • 1
    @AlgoRythm chances are it will at least notice something is wrong and warn you, giving you a rough idea where it happens. Even if smart pointers can be a bit harder to trace, valgrind has ways to help you. For example the heap profiler might come in handy to see which objects are being allocated a lot. It's one of the best tools for a c++ dev, hands down
  • 1
    @Hazarth Yeah, I used the visual studio heap profiler and it's a really good diagnostic tool
  • 3
    Our prof used to beat us if we were caught with any memory leaks in our code
  • 2
    C++ allows you to customize your classes by picking individual answers to questions like:

    - do you want polymorphism?
    - should polymorphism actually work?
    - should the subclasses leak?
  • 2
    @lorentz oh I have a good one too: do you want schroedingers polymorphism? Then just implement the public virtual functions as private and see what happens!
  • 0
    @LotsOfCaffeine is it undefined? I want to know! 😂
  • 0
    @LotsOfCaffeine subscribed to question
  • 0
    @LotsOfCaffeine I can't fathom why this is legal. It has literally no legitimate use cases.
  • 0
    @lorentz Well maybe the derived class is more modest than it's predecessors?? It won't just open up its virtual functions for any old object that asks?
  • 1
    @Lensflare not sure if it's undefined, but it is definetly weird

  • 1
    @LotsOfCaffeine just added __PRETTY_FUNCTION__ to my list of things I know. Looks like it might me a gcc-only extension though.

    Edit: in visual c++ __FUNCSIG__
  • 1
    @AlgoRythm yeah its gnu specific, though I think clang has something with a similar name

    __FUNCTION__ is standard, though I think it stems from C and is only the functions name, not the return type, class, namespace, template arguments, etc
Add Comment