Quiz Entry - updated: 2026.07.10
How do you implement load-time interpositioning with LD_PRELOAD?
Build a shared library that defines a function with the same name, load it ahead of libc with LD_PRELOAD, and call the real one via dlsym(RTLD_NEXT, ...).
// mymalloc.c
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void *malloc(size_t size) {
// Get pointer to real malloc (first time only)
static void *(*mallocp)(size_t) = NULL;
if (!mallocp) {
mallocp = dlsym(RTLD_NEXT, "malloc");
if (dlerror() != NULL) exit(1);
}
// Call real malloc
void *ptr = mallocp(size);
// Log the call
fprintf(stderr, "malloc(%lu) = %p\n", size, ptr);
return ptr;
}
Compile as shared library:
$ gcc -shared -fPIC -o mymalloc.so mymalloc.c -ldl
Use with any program:
$ LD_PRELOAD=./mymalloc.so ./hello
malloc(10) = 0x55e5bc3832a0
hello, world
Key: dlsym(RTLD_NEXT, "malloc") finds the NEXT malloc in the search order (the real one in libc).
Go deeper:
Rafał Cieślak — building an LD_PRELOAD wrapper step by step — compiling the
.so, preloading it, and calling through to the real function.