Why does the memory allocated from inside the DLL become invalid after FreeLibrary ()?

I had this error today, which turned out because I used the string allocated from inside my DLL after calling FreeLibrary() .

This is a simple crash reproducing example. This happens in the DLL:

 void dllFunc(char **output) { *output = strdup("Hello"); // strdup uses malloc } 

This is the exe that loads the dll:

 void exeFunc() { char *output; dllFunc(&output); std::string s1 = output; // This succeeds. FreeLibrary(dll); std::string s2 = output; // This crashes with access violation. } 

I read the FreeLibrary() documentation, but I could not find anything about the memory becoming invalid after calling it.

Edit

I just realized that I used the VS2008 toolchain for DLLs using the VS2010 toolkit for EXE (I used VS2010 as an IDE for both, but you can choose the toolchain from the project settings). Installing tool bindings on VS2010 for the DLL also removed the failure.

+4
source share
2 answers

If you choose static linking to the MSVCRT library (C Runtime), you will get the description that you are describing. The same thing happens if your EXE and DLL are dynamically linked to the MSVCRT DLL but use different versions. Or, if they match the same version, but one uses DEBUG and the other uses RETAIL. In other words, memory is used as well as the lifetime of the MSVCRTxxx.dll file used for allocation. I just saw your update to your question - yes, mixing and matching CRT between VS 2008 and 2010 is the exact cause of the failure.

If your DLLs and EXEs are dynamically linked to the same version of the MSVCRT DLL, you are sharing a lot of memory and you are avoiding the problems you have.

The standard practice is this: if the exported DLL function returns everything that needs to be "released" or "released" later, then the standard practice is to provide an extra function exported from the DLL to handle de-allocation.

You can configure the EXE and C Runtime DLL connections from the code page for the C / C ++ project settings in your project.

Image here: http://imgur.com/uld4KYF.png

uld4KYF.png

+6
source

This is because each Dll creates its own heap of memory (which malloc and her friends C will use together with new internally, usually through HeapAlloc ), and when the Dll is freed, then heap of it.

See this MSDN article for additional warnings in Dll. if you do not use a specialized memory allocator that is common to all your binaries, you need to save dynamically allocated memory in the module he created (if you cannot guarantee 100% that the object will not survive its creator).

+5
source

All Articles