Frank
Frank

Reputation: 47

Which malloc will be called?

I want to adopt jemalloc in my project. In order to call the malloc() function in jemalloc, I included jemalloc/jemalloc.h in the .cpp files. However, inevitably I should also call some function provided in cstdlib.h. So both jemalloc/jemalloc.h and cstdlib.h are included. I am wondering in this case, which malloc() will be called? And how can I guarantee the malloc() from jemalloc will be called? Thanks in advance!

Upvotes: 1

Views: 1016

Answers (2)

Jason Evans
Jason Evans

Reputation: 116

You need to link your application against the jemalloc library (add -L/path/to/jemalloc/lib -ljemalloc to the link command), which will cause the dynamic loader to resolve all calls to malloc(), free() etc. to the jemalloc versions. An easy way to tell if jemalloc is actually being used is to define MALLOC_CONF=stats_print:true in the environment, which will cause jemalloc to dump statistics to stderr just before program exit.

Upvotes: 4

chrisaycock
chrisaycock

Reputation: 37930

You have to tell the linker to use jemalloc, which you can do by setting an environment variable before running your program:

LD_PRELOAD=/path/to/lib/libjemalloc.so.1 your_program

Upvotes: 2

Related Questions