c++c++11dllloadlibrary

Should FreeLibrary be called at the end of the program?


I haven't found this in the documentation: if I need a DLL handler until the end of the program, should I still call FreeLibrary before my caller program ends, or it's not required?


Solution

  • It is best practice to always call FreeLibrary for any corresponding LoadLibrary call. However, skipping that call and just ending your program will likely not cause any serious issues, as terminating the calling process would appear to have the same effect as reducing the 'reference count' for your DLL (as calling FreeLibrary will do).

    From the Microsoft documentation (bolding mine):

    The reference count is decremented each time the FreeLibrary or FreeLibraryAndExitThread function is called for the module. When a module's reference count reaches zero or the process terminates, the system unloads the module from the address space of the process. Before unloading a library module, the system enables the module to detach from the process by calling the module's DllMain function, if it has one, with the DLL_PROCESS_DETACH value. Doing so gives the library module an opportunity to clean up resources allocated on behalf of the current process. After the entry-point function returns, the library module is removed from the address space of the current process.

    One reason why it is best to explicitly call FreeLibrary() is that you can then deal with the situation if/when that call returns a failure (i.e. zero) status. The details of exactly how or why your DLL would not unload properly are beyond the scope of this answer, but you may find this discussion helpful: What to do when FreeLibrary API call fails?

    Another reason would be that any future developers of your code may not realize that you are using program termination to implicitly unload the DLL and that, in some circumstances, could cause issues further down the road.