I've come across a small problem while monitoring malloc and free trough the use of function interposition.
When performing the function interposition for just malloc, it works as exepcted. However, when trying to interpose free as well it ends up in a loop; i seems like free is recursivly invoked but i just dont know why.
This is the code for the malloc and free functions. (mod_malloc_free.c)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdint.h>
#include <dlfcn.h>
void* malloc(size_t size) {
static void* (*real_malloc)(size_t) = NULL;
printf("%s\n", "inside shared malloc");
if(!real_malloc)
real_malloc = dlsym(RTLD_NEXT, "malloc");
void * p = real_malloc(size);
printf("malloc(%d) = %p\n",size, p );
printf("%s\n", "returning from shared malloc");
return p;
}
void free(void* ap ) {
static void (*real_free)(void*) = NULL;
printf("inside shared free...\n");
if(!real_free)
real_free = dlsym(RTLD_NEXT, "free");
printf("free = %p\n", ap);
real_free(ap);
}
The main simply consists of:
#include <stdio.h>
#include <malloc.h>
int main(void) {
void * p = malloc(123);
printf("p = %p\n",p );
free(p);
return 0;
}
Compiled as:
gcc -shared -ldl -fPIC mod_malloc_free.c -o libcustom.so
gcc -o smallMain -Wall smallMain.c
LD_PRELOAD=./libcustom.so ./smallMain
Best regards
Nyfiken