Rizwan Hanif
Rizwan Hanif

Reputation: 153

IXMLDOMDocument memory Leak Issue

I have a COM inproc server test application that uses IXMLDOMDocument to write data and send it back to COM client.I uses get_xml() to get BSTR. But when applications ends it's consuming almost > 20 MB memory while if I don't use COM inproc server it uses < 1 MB.
My COM Server Interface method is

[
    object,
    uuid(BF798ED1-DCDD-4B29-B552-3A17F1D7E4CF),
    dual,
    nonextensible,
    pointer_default(unique)
]
interface IMoLauncher : IDispatch{
    [id(1)] HRESULT GetXML([out] BSTR* bStr);
};

it's code is

STDMETHODIMP CMoLauncher::GetXML(BSTR* bStr)
{
    AFX_MANAGE_STATE(AfxGetStaticModuleState());
    BOOL result = FALSE;
    IXMLDOMDocument* pDoc = NULL;
    HRESULT hr = CoCreateInstance(CLSID_DOMDocument, NULL, CLSCTX_INPROC_SERVER,
                                  IID_IXMLDOMDocument, (void**)&pDoc);

    if ( SUCCEEDED(hr) )
    {
        result = TRUE;
        IXMLDOMNode* pEntityNode = InsertDOMElement(pDoc, NULL, L"Entity", NULL);
        SerializeXML(pDoc, pEntityNode);
        pDoc->get_xml(bStr);
        pDoc->Release();
    }
    return result;
}

And usage code in client is

CoInitialize(NULL);
IMoLauncher* launcher = NULL;
IUnknown* unknown = NULL;
HRESULT result = CoCreateInstance(CLSID_MoLauncher,NULL,CLSCTX_INPROC_SERVER,IID_IMoLauncher,(void**)&launcher);
if(result==S_OK)
{
    for(int i=0;i<iterationCount;i++)
    {
        BSTR bStr;
        launcher->GetXML( &bStr);
        printf("Iteration %d\n",i);
        ::SysFreeString(bStr);
    }
}
launcher->Release();
CoUninitialize();

Upvotes: 2

Views: 1216

Answers (2)

manuell
manuell

Reputation: 7620

The IXMLDOMNode* returned from CMoLauncher::InsertDOMElement is never released, that's a big leak.

You need to add Release calls for:

  1. The first InsertDOMElement call in CMoLauncher::SerializeXML.
  2. The InsertDOMElement calls in the loop in the same function (adding a local variable in order to do so (return value of InsertDOMElement)
  3. The InsertDOMElement call in CMoLauncher::GetXML (spotted by xMRI)

Upvotes: 1

xMRi
xMRi

Reputation: 15355

You Need to release pEntityNode too!

Every COM pointer returned by an Interface or COM function must be released. You may use smart pointers to avoid such mistakes.

Upvotes: 2

Related Questions