Allocating memory in a DLL and freeing in an EXE

Posted by Matt | Filed under , , ,

I want to clarify something that I alluded to in a previous post.

There are some issues when you try to allocate memory (either using new or malloc, etc.) in one binary (DLL, EXE, etc.) and freeing that memory (using delete, free, etc.) in another binary (DLL, EXE, etc.). 

The main problem comes from the C runtime library.  This is where the selection of the runtime linking is critical.

If you link to the C runtime as a static library (eg. Multithread or Multithread Debug), then you have 2 different C runtimes in the 2 different binaries.

A solution to this problem is to link to the C runtime as a dynamic library (eg. Multithread DLL or Multithread DLL Debug).  This allows the different binaries to share the C runtime that's in the DLL.

Of course, this requires your application to ship and install the MSVCR90.DLL (if you're using Visual Studio 2008).  But it gives you the freedom to allocate and deallocate memory anywhere inside your application logic.

Comments are closed