Search code examples
c++winapidllmemory-managementcrt

Does a memory leak at unload of a DLL cause a leak in the host process?


Consider this case:

dll = LoadDLL()
dll->do()

...
void do() {
    char *a = malloc(1024);
}
...

UnloadDLL(dll);

At this point, will the 1k allocated in the call to malloc() be available to the host process again? The DLL is statically linking to the CRT.


Solution

  • No, you do not leak.

    If you mix dll models (static, dynamic) then you can end up with a memory error if you allocate memory in a dll, that you free in a different one (or freed in the exe)

    This means that the heap created by the statically-linked CRT is not the same heap as a different dll's CRT.

    If you'd linked with the dynamic version of the CRT, then you'd have a leak as the heap is shared amongst all dynamically-linked CRTs. It means you should always design your apps to use the dynamic CRTs, or ensure you never manage memory across a dll boundary (ie if you allocate memory in a dll, always provide a routine to free it in the same dll)