Overriding ‘malloc’ using the LD_PRELOAD mechanism

I always do it this way: #define _GNU_SOURCE #include <stdio.h> #include <dlfcn.h> static void* (*real_malloc)(size_t)=NULL; static void mtrace_init(void) { real_malloc = dlsym(RTLD_NEXT, “malloc”); if (NULL == real_malloc) { fprintf(stderr, “Error in `dlsym`: %s\n”, dlerror()); } } void *malloc(size_t size) { if(real_malloc==NULL) { mtrace_init(); } void *p = NULL; fprintf(stderr, “malloc(%d) = “, size); p = … Read more

What do ‘statically linked’ and ‘dynamically linked’ mean?

There are (in most cases, discounting interpreted code) two stages in getting from source code (what you write) to executable code (what you run). The first is compilation which turns source code into object modules. The second, linking, is what combines object modules together to form an executable. The distinction is made for, among other … Read more

What happens to global and static variables in a shared library when it is dynamically linked?

This is a pretty famous difference between Windows and Unix-like systems. No matter what: Each process has its own address space, meaning that there is never any memory being shared between processes (unless you use some inter-process communication library or extensions). The One Definition Rule (ODR) still applies, meaning that you can only have one … Read more