DLL 卸载时内存泄漏
C++ 控制台应用程序在运行时使用 LoadLibrary() 函数加载 DLL,然后调用 DLL 导出的一些函数。一旦应用程序使用完 DLL,它就会调用 FreeLibrary() 函数来卸载 DLL。 当 DLL 卸载时,由 DLL 函数调用引起的内存泄漏是否也会被删除,或者它们将保留在那里直到应用程序终止?
A C++ console application loads a DLL at run time using LoadLibrary() function and then calls some of the functions exported by the DLL. Once the application is done with the DLL, it calls FreeLibrary() function to unload the DLL.
Will the memory leaks caused by the DLL function calls also get removed when the DLL is unloaded or they will remain there untill the application terminates?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
内存泄漏仍将存在。操作系统不关心哪个DLL分配了内存,它只关心哪个进程分配了内存。
The memory leaks will remain. The OS doesn't care which DLL allocated the memory, it only cares about which process allocated the memory.
好吧!所以这是解决这个问题的方法。
由于它是一个控制台应用程序,我假设您正在创建应用程序,在这种情况下,操作系统会为您分配堆栈/virtualmem 和堆,您将在堆上创建对象。一般来说,这些细节是从我们这里抽象出来的,因为我们只需使用运算符“new”!
这是可能有效的方法 -
获取操作系统提供的默认堆的句柄 - GetProcessesHeap();
并使用 HeapFree() 在 freelibrary 之后释放堆!这将清除分配给您的整个堆,但这也可能清除其他动态分配的内容。
这就是让它发挥作用的方法-
在加载 DLL 之前,使用 HeapCreate() 创建一个动态分配 DLL 所需的私有堆。
使用 HeapAlloc 和 HeapDealloc 而不是 new/delete 使用私有堆句柄从 dll 创建对象。
使用完库后,使用 heapdestroy() 释放堆!
Alright! so here is how you could solve this problem.
since its a console application I assume you are creating the application in that case the OS allocates stack/virtualmem and the heap for you where you would create the objects on heap. generally those details are abstracted from us as we simply use operator "new"!
here is what might work -
get a handle to the deafault heap provided by your OS - GetProcessesHeap();
and free the heap after freelibrary using HeapFree()! this would clear the entire heap allocated to you but this might clear other dynamically allocated stuff as well.
this is how you can make it work-
before loading the DLL create a private heap required for dynamic allocation of stuff from your DLL using - HeapCreate().
use HeapAlloc and HeapDealloc instead of new/delete to create objects from your dll with your private heap handle.
free the heap using heapdestroy() once you are done with using the library!