I am trying to hack the malloc function to call my malloc function first.Once my malloc function is executed within that, I want to invoke the standard malloc. But, I am getting
To override shared functions you need to compile your own shared library and preload it via the LD_PRELOAD environment variable.
#define _GNU_SOURCE
#include
#include
#include
void *malloc(size_t size) {
printf("called..my malloc\r\n");
void *(*original_malloc)(size_t size);
// Find original malloc function
original_malloc = dlsym(RTLD_NEXT, "malloc");
if ( dlerror() != NULL)
{
puts("malloc symbol not found..");
exit(1);
}
printf("This should call actual malloc now..\r\n");
return (*original_malloc)(size);
}
$ gcc -Wall -fPIC -shared -o mymalloc.so mymalloc.c -ldl
$ LD_PRELOAD=./mymalloc.so ./prog
Now your program will use malloc from preloaded library.