C++ – Issues with Statically Linking STL into Multiple Shared Libraries

clibrariesstatic-linkingstl

Here is the scenario:

  1. libA.so and libB.so both statically link to the same STL.
  2. libA.so has a public API that returns a std::string.
  3. libB.so calls this function and receives a copy of the string.
  4. When libB.so's copy of the string goes out of scope the string's destructor is called.
  5. The application seg faults attempting to free the copied string.

I've read elsewhere that statically linking like this is bad but I'd like to better understand why it's bad. Can anyone explain why the above sequence would crash?

Best Answer

Let's think about this very carefully. libA.so is statically linked with the STL. However, the STL does not exist in isolation, it requires the C runtime (CRT). They both reside in the libstdc++.a static library. This means that libA.so and libB.so have separate CRT data structures. In particular, the heap used by libA.so is different from the heap used by libB.so. Allocating a string from libA's runtime heap and attempting to free from libB's runtime will simply not work because libB's runtime has no records of allocating the string. The only way to correctly destruct the string is by calling the destructor within libA.so.

One might ask: but libB.so receives a copy of the string, right? Yes that's right but who has allocated this copy? It has been allocated using the copy constructor within the context of the libA's runtime.

That said, you can still use the string from libB.so. You just cannot destruct it from there.

You can also let libB receive a pointer to the string and then creating a copy of it within the context of the libB's runtime. That copy can be destructed by libB.

And that's why static linking is sometimes bad.

Related Topic