CDOEXM CreateMailbox is leaking memory
I had a case recently where the customer had built an application to help manage their Active Directory environment. Part of this application used CDOEXM to create new mailboxes for their new user accounts. This is a common use of CDOEXM - nothing wrong so far. What this particular application was doing though was that when it had new work to do, it would spawn a new thread. On that new thread, they would CoInitialize, do their CDOEXM work, then CoUninitialize. The customer was reporting that the process leaked memory. Sure enough, commenting out the call to CreateMailbox prevented the leak.
After debugging, I discovered that some of the functions in the CreateMailbox code path use static variables. Each time CDOEXM is loaded and the execution hits those static variables for the first time, they'll be created in the static heap. Since his application spawned a new thread that did this for each user, the memory would increase by this amount each time. So the leak wasn't really a leak as much as it was just the way static variables work and the way his application was structured simply used an increasing amount of memory.
By moving his loop inside the CoInitialize/CoUninitialize block, the memory usage remained static.
So it seems that CDOEXM is not going to work well in an architecture like this. Here are some ideas for how to architect your solution to not run into this problem:
- Spawn a new process to do your CDOEXM work (which will terminate when finished).
- Create a low (finite) number of background worker threads you can persist throughout the lifetime of your process that you can queue CDOEXM work to. This will allow you to call CoInitialize/CoUninitialize a controlled number of times.
- Put the CDOEXM code in a COM+ component and call it from your application. This way, your CDOEXM code just gets loaded in dllhost and you don't have to worry about it. Here's an article Matt wrote about how to do this in managed code.