I am trying to create wrapper functions for free
and malloc
in C to help notify me of memory leaks. Does anyone know how to declare these functions so when I call malloc()
and free()
it will call my custom functions and not the standards lib functions?
You have a few options:
GLIBC-specific solution (mostly Linux). If your compilation environment is glibc
with gcc
, the preferred way is to use malloc hooks. Not only it lets you specify custom malloc
and free
, but will also identify the caller by the return address on the stack.
POSIX-specific solution. Define malloc
and free
as wrappers to the original allocation routines in your executable, which will "override" the version from libc. Inside the wrapper you can call into the original malloc
implementation, which you can look up using dlsym
with RTLD_NEXT
handle. Your application or library that defines wrapper functions needs to link with -ldl
.
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
void* malloc(size_t sz)
{
void *(*libc_malloc)(size_t) = dlsym(RTLD_NEXT, "malloc");
printf("malloc\n");
return libc_malloc(sz);
}
void free(void *p)
{
void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free");
printf("free\n");
libc_free(p);
}
int main()
{
free(malloc(10));
return 0;
}
Linux specific. You can override functions from dynamic libraries non-invasively by specifying them in the LD_PRELOAD
environment variable.
LD_PRELOAD=mymalloc.so ./exe
Mac OSX specific.
Same as Linux, except you will be using DYLD_INSERT_LIBRARIES
environment variable.