c++tcmalloc

Using tcmalloc in a shared library


I have many executables that are linked with tcmalloc (.a). I usually do it at the executable level, so that any shared library loaded by the executable benefits from tcmalloc.

However, I have a scenario where I need to provide a .so library to an user.

Is it ok to use tcmalloc in that shared library?

What happens if the user's executable itself is not linked with tcmalloc?

Thanks.


Solution

  • Is it ok to use tcmalloc in that shared library?

    It depends on a few things:

    What happens if the user's executable itself is not linked with tcmalloc?

    One of the two things can happen:

    1. malloc is already a resolved symbol in user's application/process. In this case your .so uses that malloc. That happens when the user loads your .so with dlopen.
    2. malloc is not resolved yet, so that user's application/process uses malloc from tcmalloc from your .so. That happens when the user links against your .so in linker command line and your .so comes before -lc.

    It may be most robust for your .so to not link tcmalloc at all. The user of the application can then decide which malloc implementation to use either by linking against tcmalloc or other allocator, or trying different allocators by pre-loading them at run-time using LD_PRELOAD.

    You may like to learn how Unix linkers work to answer such questions yourself in the future.