Vitalii
Vitalii

Reputation: 4793

How Linux decides what `malloc` to use?

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?

Upvotes: 6

Views: 581

Answers (2)

Šimon Tóth
Šimon Tóth

Reputation: 36433

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.

Upvotes: 2

Harald
Harald

Reputation: 3180

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.

Upvotes: 1

Related Questions