3

I have a native C++ ATL in-proc COM server. A separate test program

  • calls CoInitialize(),
  • calls CoCreateInstance(), then
  • calls Release() on the pointer,
  • then calls CoUnitialize() and exits.

If I run the test program under Visual C++ debugger the debug CRT reports a single memory leak and each time the allocation number is the same.

I used an allocation hook and found out that the object not being returned to the heap is the class factory object.

So basically the following happens:

  • the program calls CoCreateInstance()
  • COM internally calls DllGetClassObject()
  • ATL instantiates the factory and passes ownership to the caller (COM internals)

and then the factory is never released - I don't see enough calls to Release() of the class factory.

What is happening? Is that a defect in COM runtime?

4
  • I'm not actually sure it makes a difference when calling CoUnitialize() but does you DLL export DllCanUnloadNow ? Commented Oct 27, 2010 at 13:39
  • @Alexandre Jasmin: Yes, it does. DllCanUnloadNow() should only affect unloading the library, not releasing the factory. Commented Oct 27, 2010 at 13:48
  • I'm just musing out loud, but does explicitly calling either CoFreeUnusedLibraries or CoFreeAllLibraries make any difference? Commented Oct 27, 2010 at 14:39
  • @Phil Booth: Tried both - doesn't change anything. Commented Oct 28, 2010 at 7:53

1 Answer 1

2

Turns out it's a problem of ATL implementation.

The server uses a global CComModule class instance. When CComModule::DllClassObject() is called it creates a class factory instance and caches it in the map referenced by the CComModule object. So in fact CComModule object owns the class factory. When CComModule destructor runs it doesn't release cached class factories.

In order to release all cached class factories CComModule::Term() method should be called before the server is unloaded. IMO the cleanest way to achieve this is to derive from CComModule and call CComModule::Term() in the derived class destructor.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.