Reputation: 5474
I have been wandering about the best way to sandbox memory leaks in 3rd party libraries when using them from the .Net framework.
I have a 3rd party library, written in C++/cli, that leaks a lot of memory.
Is there anyone out there who has found an elegant way of cleaning up unmanaged memory leak using .Net?
Best regards,
Upvotes: 3
Views: 1367
Reputation: 78
Unmanaged object: Unmanaged objects are created outside the control of .NET libraries and are not managed by CLR. Examples of such unmanaged code are COM objects, file streams, connection objects, Interop objects. (Basically, third-party libraries that are referred to in .NET code.). GC can not handle the unmanaged object by itself because it has no idea about it. So, for example, let's say you used a pointer in your C++/CLI library class, and you delete that pointer in the destructor(~) of that class. This will lead to memory leak because, In C++/CLI, the notation ~ is already reserved for deterministic destructors (because all destructors are deterministic in C++). So, here we must use the notation ! instead.
C++/CLI example of IDisposable, Finalizer and GC.SuppressFinalize()
ref class ClassName {
public:
ClassName() : m_isDisposed(false) {
m_unmanagedData = new CustomObject();
}
~ClassName() {
if (m_isDisposed)
return;
this->!ClassName();
m_isDisposed = true;
}
// Finalizer
!ClassName() {
delete m_unmanagedData;
}
private:
bool m_isDisposed;
CustomObject * m_unmanagedData;
};
Follow this documentation guideline from Microsoft to find out the memory leak in your C++/CLI library Find memory leaks with the CRT library
Upvotes: 0
Reputation: 33252
No way, unless of course you can modify and fix the C++ code, but probably this is not an option. I had the same problem in the past, solution is host the leaking code in a process ( note: an app domain is not enough ) and shut down periodically that process. Use some IPC technique to comunicate with that process instance. You can optional create a pool of two of that process to apper reactive even when you need to shutdown a process, so you can easily switch to the other instance, already running.
Upvotes: 2
Reputation: 7960
You can run a memory checker of your choosing to find the leaks. this is a pretty straight forward process. I use Intel Inspector (Part of Intel parallel studio) but others will do the trick.
In order to sandbox allocations, you can use a malloc
replacement such as google_malloc and modify it to have a free_all_memory
function if it doesn't already have one.
This isn't very elegant, but if your unmanaged code is in really bad shape, that's an option.
Upvotes: 0