C++ – strategies to keep tabs of memory leaks in non memory-managed languages

cmemory

When it comes to non memory managed languages such as C, C++ or Fortran (my case), it becomes increasingly difficult to keep track of memory allocation/deallocation, especially when ownership must be shared. I implemented refcounting for my objects, but this makes it even more complicated as there's no place where an object gets deallocated. Every reference decrement is a potential deallocation point.

So it's now more and more difficult for me to track down memory leaks. I was wondering about some established techniques to deal with memory management in non-memory managed languages, apart from valgrinding your way around.

Edit: I am more interested in active programming strategies (which are general).

Best Answer

You've already covered them.

If shared ownership causes memory management issues, work your design away from shared ownership. Usually this involves designating one part of the code as the owner, and thus responsible for deallocation. Weak pointers (or the equivalent) can help this programmatically. RAII can be more liberally applied when single ownership exists.

If you have refcounting (or another mechanism for auto-deallocation) then you need not care if/where the deallocation occurs. You simply need to test/prove that the structure will correctly deallocate memory when it is supposed to.


A few other things to focus on:

  • Memory management likes patterns. When your code follows consistent patterns, it will have consistent behavior as far as memory management is concerned. When you do detect memory leaks, you can then focus on the exceptional cases, making them easier to find.
  • Shrink your scope. If the objects only live within an isolated scope, it's easier to reason about ownership and their lifetimes.
  • Only allocate what you need. Better than small scopes is no scope. If you don't need to allocate memory (within reason), don't.
Related Topic