Home:ALL Converter>Error when trying to link to a shared library I created using LD_PRELOAD

Error when trying to link to a shared library I created using LD_PRELOAD

Ask Time:2021-01-12T17:28:44         Author:driveaway

Json Formatter

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.

Author:driveaway,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/65681159/error-when-trying-to-link-to-a-shared-library-i-created-using-ld-preload
yy