Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Linux decides what `malloc` to use?

Tags:

c++

c

linux

I know how to replace malloc with LD_PRELOAD; library that preloaded gets priority, so if we preload jemalloc, executable gets its malloc version. However, when we build application with -ljemalloc, we also link it against glibc. How Linux knows that it has to use jemalloc malloc and not glibc one? What if I will link both jemalloc and tcmalloc, we'll have 3 malloc now, what and why Linux (or may be the linker, I am not sure) will select?

like image 883
Vitalii Avatar asked Nov 26 '15 19:11

Vitalii


2 Answers

You can check the order of libraries being loaded by running:

strace -ff -s 999 YOUR_BINARY 2>&1 | grep -e 'library1' -e 'library2'

The order should match the output from ldd YOUR_BINARY.

And yes, as already noted, the first library will get priority.

like image 195
Šimon Tóth Avatar answered Sep 19 '22 13:09

Šimon Tóth


That is interesting. Some OSes warn you about replicated symbols at link time (AIX, IIRC). Linux does not.

Something similar happens when instrumenting MPI apps through the PMPI interface. In this case the order is important. If the instrumentation tool comes after the MPI library, then the interposition does not work. So I'd think than in your case would be the same. The linker will choose by their given order.

like image 30
Harald Avatar answered Sep 19 '22 13:09

Harald