So I have a DLL I wrote in C++.
However, it allocates memory using GlobalAlloc(). To avoid memory leaks, I want to keep track of these allocations and de-allocate all of them on the destruction of the DLL.
Is there any way to write a function that will be called when my DLL is unloaded?
One thing I can think of is creating a global object in my DLL and writing the memory free calls in its destructor, but this seems like overkill.
My other idea is to just rely on the operating system to free the memory when the DLL unloads, but this seems dirty.
That’s possible, although I believe exactly when your object’s destructor will be called will be undefined.
You might be interested in
DLL_PROCESS_DETACH, and although you should avoid doing anything significant inDllMain, it seems deallocating resources is acceptable here. Note the caveats:You might need to elaborate on why your DLL can hold on to memory, if you have numerous objects created by the DLL, they should have a defined lifecycle and clean themselves up at the end of their life.
If they’re not objects (i.e. memory being allocated and returned to the caller via functions) why not put the responsibility back onto whoever is consuming your DLL? They can free the memory. The Terminal Services library follows this pattern (
WTSFreeMemory).If the resources are long-lived and must exist for the lifetime of your library, let the consumer control the lifecycle of your library. Write two functions:
MyFrameworkStartupandMyFrameworkShutdownas appropriate. Winsock follows this pattern (WSAStartupandWSACleanup).You’ll be okay if the process is exiting:
Make sure you read the whole article and comments and understand it before implementing the "do nothing" strategy.