The LoadLibraryA method returns error code 1114 (ERROR_DLL_INIT_FAILED) after more than 1000 cycles of loading/unloading


I'm programing on C++, I'm using Visual Studio 2008, Windows XP, and I have the following problem: My application, that is a DLL that can be used from Python, loads an external dll, uses the required methods, and then unloads this external Dll. It's working properly, but after more than 1000 cycles the method "LoadLibraryA" returns a NULL reference.

The main steps are:

h = LoadLibraryA(dllfile.c_str());
DWORD dw = GetLastError(); 

The error got is:

1114 (0x45A) A dynamic link library (DLL) initialization routine failed.

The Dll is unloaded by using the following:


Where mDLL is defined like this:


First alternative tried: Just load the Dll only once, and unloaded it when the application ends. This fix the problem but introduces a new one.

When the application ends, instead of first executing the DllMain method of my applicaion, wich unloads the external DLL, is executing first the DllMain method of the other Dll. This cause the following error because my application is trying to unload a Dll that was unload by itself previously.

"Unhandled exception at 0x04a00d07 (DllName.DLL) in Python.exe: 0xC0000005: Access violation reading location 0x0000006b".

Any suggestion will be welcomed. Thanks in advance. Regards.

asked on Stack Overflow Jun 10, 2010 by Javier • edited Jun 10, 2010 by R Samuel Klatchko

1 Answer


Make sure that initialization code of the loaded/unloaded library doesn't leak memory. Many libraries expect to be loaded only once and not always clean up their resources properly.

E.g. in C++ file at the top level one can declare and initialize a variable like this:

AClass *a = new AClass(1,2,3);

The code would be executed when library is loaded automatically. Yet, now, it is impossible to free the hanging instance as library doesn't know precisely when/how it is going to be unloaded. In the case one can either replace "AClass *a" with "AClass a" or write your own DllMain for the library and free resources on DLL_PROCESS_DETACH.

If you have no control over the library's code, then it might make sense to create a cache of loaded libraries and simply never unload them. It is very hard to imagine that there would be unlimited number of libraries to overload such cache.

answered on Stack Overflow Jun 10, 2010 by Dummy00001

User contributions licensed under CC BY-SA 3.0