Search code examples
c++cdllstatic-linkingdynamic-linking

What problems can linking both static and dynamic libraries into the same executable cause?


I was asked this question on a job interview today. Unfortunately, I am not sure that I have reproduced it here correctly. I just remember, that I did not understand it very well. The question might have been

"What problems can loading statically and dynamically compiled dlls cause?"

I did not know the answer, but the interviewer told me that there are at least two main problems:

  1. The runtime library: there can be some incompatible allocations and de-allocations of memory.

  2. Unfortunately here we got interrupted and we did not get back to this question.

Please, could you help me understand what this question might have been, as well as what is the answer?

I also did not understand the first point very well. I thought there can be only one malloc in a program, am I wrong?


Solution

  • Let's say that A.dll links statically with standard library version 1.0. And it has a function that looks like this:

      char * f() {
         return malloc( 100 );   // uses malloc 1.0
      }
    

    Now lets say there is another library B.dll that links dynamically with A.dll and statically with standard library version 1.1. It has a function that looks like this:

       void g() {
          char * p = f();  // returns the result of malloc 1.0
          free( p );   // uses free 1.1
       }
    

    You then probably (I say "probably" because none of this is standardised) have a pointer that was dynamically allocated with standard library 1.0, but that was freed with version 1.1. This can often lead to severe and hard to diagnose problems.