0

I would like to expand an existing tool with the functionality of a memory debugger (just leak detection).

I know that some memory debuggers work by replacing malloc/free and keeping track of what is pending to be freed and who allocated it; or by running the process on sort of a virtual machine and monitoring memory accesses.

I want to know if it makes sense to use ptrace() to set breakpoints on malloc/free, instead rebuilding with dmalloc for example, and monitoring allocations in a separate process. Would it be too slow? Does any other tool work this way?

imreal
  • 10,178
  • 2
  • 32
  • 48
  • 3
    I don't see any reason you couldn't do it that way (just for leak detection), but I question whether it would be worthwhile except as an exercise. Memory debugging is hard to do well, and valgrind is hard to beat unless you have specialized needs where its performance is prohibitive. Also, "leak detection" is usually a broken idiom; it will find all the non-issue leaks (stuff not freed before exit) but can't find any of the problematic ones (allocations whose lifetimes never end until exit even though they're no longer in use). – R.. GitHub STOP HELPING ICE Nov 26 '12 at 20:07
  • @Nick, I'm currently doing the exact same thing but I'm having problems catching leaks before the OS frees them on exit. Have you made any progress implementing this? – tay10r May 30 '13 at 05:49
  • @TaylorFlores Found out that while it works it is not the best approach, in the case of `malloc/free` that are heavily used, it adds a significant amount of lag because of all the context switches. I recommend using hooks instead, here is a simple tutorial http://www.linuxforu.com/2011/08/lets-hook-a-library-function/ – imreal Jun 14 '13 at 18:48
  • @Nick, I haven't heard of `hooks` before and it looks like that is a solution. Thanks for getting back at me, that link helps a lot. – tay10r Jun 14 '13 at 19:51
  • 1
    I wrote a prototype LLDB based tool (in Python) to do this and it was too slow for non trivial programs. – ysdx Apr 15 '14 at 12:02
  • It might be more efficient, to intercept the functions calls with LD_PRELOAD and send it via socket/shared memory/file to another process. – ysdx Apr 15 '14 at 12:11
  • Correct link for @imreal comment: https://opensourceforu.com/2011/08/lets-hook-a-library-function/ – Zzz0_o Dec 28 '18 at 07:57

1 Answers1

0

It is not practical to use a debugger and trap malloc/free calls for a few of reasons:

  1. The overhead of switching from one process to the other one is just to great on nontrivial programs.

  2. You'll end up spending a similar amount of memory to store ownership information than with other methods. (This is what I actually wanted to improve)

  3. There are quite a few functions that work the heap, and it could be easy to miss some.

imreal
  • 10,178
  • 2
  • 32
  • 48