I'm trying to test if I can override the glibc's malloc interface by linking a shared library on Linux. I don't have the details for the malloc functions yet.
So I created a nullmalloc.cpp
that has the required replacements for malloc, but all returns null. The code looks like this:
# include <cstddef>
void* malloc(size_t size) { return 0; }
void* calloc(size_t n, size_t size) { return 0; }
void free(void* ptr) { return; }
void* realloc(void* ptr, size_t size) { return 0; }
void* valloc(size_t size) { return 0; }
void* memalign(size_t align, size_t s) { return 0; }
void cfree(void* ptr) { return; }
void* aligned_alloc(size_t align, size_t s) { return 0; }
void* pvalloc(size_t size) { return 0; }
struct mallinfo mallinfo(void);
int mallopt(int cmd, int value) { return 0; }
And then I tried to make a shared library of the cpp file by these commands:
gcc -Wall -fPIC -g -c nullmalloc.cpp // creates nullmalloc.o
gcc -shared -Wl,-soname,nullmalloc.so -o nullmalloc.so nullmalloc.o // creates nullmalloc.so
When I used LD_PRELOAD to link nullmalloc.so
to a test code I wrote called test.cpp
, I got an error saying that the .so file could not be found.
The command I used with LD_PRELOAD is this:
g++ -g test.cpp -o test.o -std=c++11 LD_PRELOAD=/home/nullmalloc/nullmalloc.so
And the error I got is this:
g++: error: LD_PRELOAD=/home/nullmalloc/nullmalloc.so: No such file or directory
I'm confused because the nullmalloc.so
file exists when I use the ls
command.
[root@a nullmalloc]$ ls
nullmalloc.cpp nullmalloc.o nullmalloc.so test.cpp
I've only started studying about malloc, linux, and shared libraries, so I'm not sure where I've made a mistake. Could anyone give advice on where to start fixing?
Thank you.