Memory leak when using CoCreateInstance

I use COM to initialize a C # .NET class using unmanaged C ++ code, and I detect a memory leak even in a very simple program:

int _tmain(int argc, _TCHAR* argv[]) { CoInitialize(NULL); ComClass::IClass1 *_comClass1; HRESULT hr = CoCreateInstance(__uuidof(ComClass::Class1), 0, CLSCTX_INPROC_SERVER, __uuidof(ComClass::IClass1), reinterpret_cast<void**>(&_comClass1)); _comClass1->Release(); CoUninitialize(); return 0; } 

C # class is also super simple:

  [ComVisible(true), Guid("A95C4F43-65B0-4706-94D1-BEE2EF416766")] public interface IClass1 { } [ComVisible(true), Guid("4670C9CD-0501-4274-BF03-E1FF65A77FEC")] public class Class1 : IClass1 { public Class1() { } } 

And yet I detect memory leaks. I use GlowCode and Purify to detect leaks, but even without them I can see how memory usage is increasing.

Am I not using CoCreateInterface correctly? What am I missing?


lightening

This is a small program designed to simulate a problem. There are many CoCreateInstance calls in my real program, and the size of the virtual machine increases to about 1.5 GB, of course, this cannot be normal ... Also, I can see, using perfmon, that the private bytes of the process are growing, while like .Net CLR Byte memory in all Heaps is not. Also, GlowCode can control the changed heap and not indicate a memory leak in the managed part ...

+4
source share
1 answer

Yes, it is normal. The first call to CoCreateInstance will load the CLR into your process. Which creates the main AppDomain for loading managed code, with a bunch of garbage, a bunch of loader, and a small amount of internal data structures. Calling the Release () method of an interface pointer does not unload the CLR. It supports all future requests for loading and executing managed code. The primary appdomain is not unloaded until the process is complete.

The unmanaged memory diagnostic tool will not know that this is normal.

A true memory leak is one that increases the size of a virtual machine without an upper bound. Convince yourself that this is not a real memory leak by running this code a billion times.

+6
source

Source: https://habr.com/ru/post/1336153/


All Articles