finding who creates object via smart pointer

2019-08-08 15:54发布

问题:

I posted few days back regarding memory leaks with smart pointers. Now I am able to find out which objects are leaking memory but I am not able to figure it out from where they are leaking memory.

I am using the same code as mentioned here Detecting memory leak in reference counted objects

I have read lot of comments but none of them explains properly. I tried using macros FILE and LINE , both of them prints file and line of refmanager class .

Is there a good way to debug this issue.Please point to some nice example also.

回答1:

The easiest way is probably to use Valgrind (on Linux and Mac) and some similar tool on Windows.

You could also in the constructor of the smart-pointer take a backtrace (using the function backtrace() function on Linux and Mac) or a similar function from dbghelp.dll on windows and then save the backtrace somewhere on allocation and remove the backtrace on deallocation. Then on exit print all the remaining backtraces.



回答2:

On Windows you can use the new memory diagnostics tools in Visual Studio 2015:

  • http://blogs.msdn.com/b/vcblog/archive/2015/10/21/memory-profiling-in-visual-c-2015.aspx