Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count blocks allocated with malloc() from external program

Tags:

c

linux

malloc

I want to write a "simple" memory leak checker.

In order to do that I need to count a number of the malloc()ed memory blocks in a program, but the problem that I do not want to modify it's source.

In other words, I want to implement the following interface:

memory_check <executable name>

Where I do not have an access to the executable's source.

Firstly I supposed to try intercept a system call. But I read "So malloc doesn't invoke any syscall?" and it doesn't seem to be an idea, also because of it will extremely slow all system (as I can suppose).

Are there any other options to intercept the malloc() calls?

like image 360
Alex Avatar asked Mar 03 '13 07:03

Alex


1 Answers

If you're willing to change your interface to LD_PRELOAD=mymalloc.so <executable> you can do it like so:

  • Make a shared library that
    • Gets a handle to malloc using dlsym
    • Exposes an external void *malloc(size_t size)
    • Calls the real malloc via the handle obtained above, and also stores your debug info

Then:

  • Call the program LD_PRELOAD=mymalloc.so ./program
  • The program automatically calls your "hijacked" version of malloc

EDIT

If you don't want to change your interface but want to use this trick you can make a wrapper program that fork(2)s, sets up LD_PRELOAD and then execs your real program using its name.

like image 100
cnicutar Avatar answered Sep 20 '22 18:09

cnicutar