During my last week’s class I discussed a source-code method of finding memory leaks in C++. What do I mean by that? Source-code method is not a way of debugging a process like one could do with Valgrind on Linux or Deleaker on Windows (which I’ve used recently and really enjoyed its integration with Visual Studio). What I am referring to is a combination of #define MACRO magic and overwriting the void* operator new. A technique to keep track of all your new / new[] and delete / delete[] statements and finding A) leaks due to missing delete statements and B) mismatches between array and non array versions of said operators.
Simply by including a header file in your source code you enable this tracing capability. Though it has a limitation: unlike Deleaker or Valgrind it only works for plain vanilla new / new[] operator; my solution does not support any other form of it.


Code from the class:
newtrace.hpp (C++17 or earlier) | newtrace.cpp | README.txt
Using boost::stacktrace:
newtrace.st.hpp | newtrace.st.cpp


9 Replies to “How to detect memory leaks”

      1. I suspect it’s because the code does not synchronize access to the internal set of allocations; I will update the header file today. will update blog post once it’s checked in.

  1. also, get_new_entry_set() will throw exception in multi-thread environment. i cannot find a good solution

    1. why does it throw an exception? you can always put the same kind of lock around it like the first 2 lines in operator_delete

Leave a Reply