简体   繁体   中英

Malloc with LD_PRELOAD

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 !

The first use of stdout causes its buffer to be allocated (so that there is somewhere to put the output until ts 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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM