Create a wrapper function for malloc and free in C


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?

Best Solution

You have a few options:

  1. 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.

  2. 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");
        return libc_malloc(sz);
    void free(void *p)
        void (*libc_free)(void*) = dlsym(RTLD_NEXT, "free");
    int main()
        return 0;
  3. Linux specific. You can override functions from dynamic libraries non-invasively by specifying them in the LD_PRELOAD environment variable. ./exe
  4. Mac OSX specific.

    Same as Linux, except you will be using DYLD_INSERT_LIBRARIES environment variable.