Reputation: 7
I try to write a function malloc(). My file:
void *malloc(size_t size)
{
printf("test");
}
I compile this file on shared library .so. Now, i want to use LD_PRELOAD for use my malloc function:
export LD_PRELOAD=MY_LIB
I compile my main.c with this lib:
int main()
{
malloc(5);
return (0);
}
But when I running the executable, I have a Segmentation Fault .. (same if I execute ls, cat or other command
What is the problem ? Thanks you !
Upvotes: 0
Views: 1300
Reputation: 2335
Your malloc() does not return a valid pointer, secondly using printf() inside malloc() is risky, since printf, stdout etc might need to call malloc.
Use write(1, "test\n", 5);
instead, and returning a valid pointer should solve your problem.
Upvotes: 0
Reputation: 51
Similar to this question: Overriding 'malloc' using the LD_PRELOAD mechanism
One of the answers gave an example of how to wrap malloc. The person used fputs
to avoid malloc-printf recursion but you can also use fprintf
.
Upvotes: 0
Reputation: 241771
The first use of stdout
causes its buffer to be allocated (so that there is somewhere to put the output until t s ready to be sent). That requires the use of mallc()
. (This is not guaranteed by the standard; the standard library streams could use a separate memory allocation library. But they don't on any implementation I am familiar with.)
So malloc calls printf which calls malloc which calls printf which calls malloc (because the buffer hasn't been allocated yet) which calls printf and so on and so on. Until you run out of call stack.
You can replace malloc with the LD_PRELOAD
hack. But make sure nothing in your implementation produces a recursive call into malloc.
Upvotes: 1