I want to understand how .so works. Eventually I would like to make my own malloc(). But to get the infrastructure ready I just created a sample malloc() function and just printing inside it.
I compiled the following file (my_malloc.c):
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
void* malloc(size_t sz)
{
printf("malloc\n");
return NULL;
}
void free(void *p)
{
printf("free\n");
}
and created a .so using the following command:
gcc -shared -fPIC -o my_malloc.so my_malloc.c
Now I created a hello.c file and I am using the malloc() function in this file:
#include <stdio.h>
#include <stdlib.h>
int main() {
malloc(64);
return 0;
}
Then I've compiled this file with the following command:
gcc hello.c -o hello.o
I used LD_PRELOAD to override the standard malloc() implementation. When I run hello.o I get the segmentation fault:
LD_PRELOAD=./my_malloc.so ./hello.o
Segmentation fault
Why?