The number of blocks allocated by malloc () from an external program

I want to write a “simple” memory leak check.

To do this, I need to count the number of malloc()ed blocks of memory in the program, but the problem is that I do not want to change its source.

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

memory_check <executable name>

If I do not have access to the executable source.

First, I should try to intercept the system call. But I read “ So malloc does not cause any syscall? ” And this does not seem to be an idea, also the whole system will be extremely slow because of this (as I can assume).

Are there any other options for picking up calls malloc()?

+5
source share
2 answers

LD_PRELOAD=mymalloc.so <executable>, :

  • ,
    • malloc dlsym
    • void *malloc(size_t size)
    • malloc , ,

:

  • LD_PRELOAD=mymalloc.so ./program
  • "" malloc

, , -, fork(2) s, LD_PRELOAD, , .

+5

, malloc .so, malloc, :

#ifdef malloc
#undef malloc
#endif

static int count;
void *malloc(size_t size)
{
    count++;
    return _malloc(size);
}

LD_PRELOAD malloc.

0

All Articles