You have a few options:
-
GLIBC-specific solution (mostly Linux). If your compilation environment is
glibc
withgcc
, the preferred way is to use malloc hooks. Not only it lets you specify custommalloc
andfree
, but will also identify the caller by the return address on the stack. -
POSIX-specific solution. Define
malloc
andfree
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 originalmalloc
implementation, which you can look up usingdlsym
withRTLD_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.