gpt4 book ai didi

c++ - MSXML 内存泄漏

转载 作者:行者123 更新时间:2023-11-28 03:02:44 24 4
gpt4 key购买 nike

我必须处理一个遗留应用程序,该应用程序使用 MSXML 将测量数据写入一个简单的 XML 文件。基本上,这就是正在发生的事情:

MSXML2::IXMLDOMDocument2Ptr pXmlDocument;
HRESULT comResult = CXMLUtil::createXMLDocument(pXmlDocument);
// ... check HRESULT ...
MSXML2::IXMLDOMNodePtr pXmlMainNode = pXmlDocument.GetInterfacePtr();
MSXML2::IXMLDOMNodePtr pXmlSubNode = CXMLUtil::AppendNewElement(pXmlDocument, pXmlMainNode, RootTag, "");
// ... create further nodes ...
MSXML2::IXMLDOMNodePtr pXmlTmpNode = CXMLUtil::AppendNewElement(
pXmlDocument,
pXmlDataSetNode,
measDataTag,
measdata,
numberOfDataItems );
// ... append further items ...

在每一项之后,pXmlTmpNode.Release()叫做。最后,所有其他节点以及 pXmlDocumentReleased .

createXMLDocument定义如下:

HRESULT CXMLUtil::createXMLDocument(MSXML2::IXMLDOMDocument2Ptr &pXmlDocument) {
MSXML2::IXMLDOMDocument2 *xmlDocument = 0;
HRESULT comError = CoCreateInstance(__uuidof(MSXML2::DOMDocument),NULL,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&xmlDocument));
if (comError) return comError;
xmlDocument->put_async(VARIANT_FALSE);
xmlDocument->put_validateOnParse(VARIANT_FALSE);
xmlDocument->put_resolveExternals(VARIANT_FALSE);
xmlDocument->put_preserveWhiteSpace(VARIANT_TRUE);
MSXML2::IXMLDOMDocument2Ptr ptr(xmlDocument);
pXmlDocument = ptr;
return comError;
}

为了追加新元素(即 unsiged char 数组),应用此函数:

MSXML2::IXMLDOMNodePtr CXMLUtil::AppendNewElement(MSXML2::IXMLDOMDocument2Ptr pXMLDom, MSXML2::IXMLDOMNodePtr pParent, CComBSTR strElementName, unsigned char* pData, long nData) {
MSXML2::IXMLDOMNodePtr pData1 = pXMLDom->createElement(BSTR(strElementName));
pData1->put_dataType(CComBSTR(_T("bin.base64")));
SAFEARRAY* psa = SafeArrayCreateVector( VT_UI1, 0L, nData);
psa->pvData = pData;
VARIANT var;
VariantInit(&var);
var.parray = psa;
var.vt = (VT_ARRAY | VT_UI1 );
pData1->nodeTypedValue = var;
pParent->appendChild(pData1);
SafeArrayDestroy(psa);
return pData1;
}

不管天气如何#import <msxml4.dll>#import <msxml6.dll>使用,似乎有内存泄漏。自 measdata等可能很大,这是一个很大的问题。我可以做些什么来使代码工作吗?谢谢,马修

最佳答案

MSXML2::IXMLDOMDocument2 *xmlDocument = 0;
HRESULT comError = CoCreateInstance(__uuidof(MSXML2::DOMDocument),
NULL,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&xmlDocument));
...
MSXML2::IXMLDOMDocument2Ptr ptr(xmlDocument);
pXmlDocument = ptr;

此代码泄漏 xmlDocumentptr(xmlDocument) 做了一个额外的 AddRef,但是对于 xmlDocument 超出范围没有 Release。你到处都使用智能指针,没有理由不在这里也使用一个,也许是这样的:

MSXML2::IXMLDOMDocument2Ptr xmlDocument;
HRESULT comError = CoCreateInstance(__uuidof(MSXML2::DOMDocument),
NULL,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&xmlDocument));
...
pXmlDocument = xmlDocument;

关于c++ - MSXML 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20348974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com