Search code examples
cvisual-c++dynamic-linkingstatic-linkingmsvcrt

Memory Allocation in Static vs Dynamic Linking of C Runtime


My program's architecture involves plugins (dlls) and the exe (obviously). We are the only plugin provider. I was told that allocating memory in a plugin and then freeing it in the exe code was a potential problem if we statically linked the c runtime. However, if we dynamically linked it, there was just one heap and the c runtime had access to all of it. We switched to dynamic linking on the basis of this advice, but all we've seen from the switch is headaches and trouble related to distribution and installation of the new runtimes. (Don't know what we avoided in terms of memory allocation problems.)

What are the memory allocation implications? Say a plugin allocates memory and the exe frees it. Is there different behavior between the static vs dynamically linked c runtime? Will we have trouble statically linking the c runtime if we use plugins? If we switch back to static linking, will that mess up the memory leak detection and crash dump reporting?

Is in line with some questions raised by comments on Which VC++ runtime version do I choose - static or dynamic? specifically Which VC++ runtime version do I choose - static or dynamic?

There is also some discussion at http://msdn.microsoft.com/en-us/library/abx4dbyh(v=VS.100).aspx.


Solution

  • If you want to allocate from the heap in one module, and free in another then you simply have to dynamically link the runtime. What's more, all parties must dynamically link the same runtime. Once you do that then there will be no problems.

    Now, this is quite a severe constraint to impose on your plugins and you should think twice before doing it. Forcing all plugin authors to upgrade in lock-step with you is a heavy imposition. I would recommend that you consider refactoring your interface so that allocations are always paired with deallocations within a single module. This lifts the constraints I describe above and makes life easier for your plugin authors.

    As for why you are still suffering from runtime errors, that's hard to tell. My guess is that not all modules are linking against the same version of the runtime.


    In the comments you state that you control all plugins. That means the constraints I discuss above are not an imposition since it is easy for you to use the same compiler version for all modules. However, the rules for dynamic linking with cross-module heap access remain. You must use dynamic linking against the same single version of the runtime.