关于CString的AllocSysString函数的内存泄露

咔复咔 2010-04-14 07:24:20
今天用到一段以前写的读取xml文件的一段代码 里面有关于CString的AllocSysString的内存释放的注释 突然想起了以前写这段代码是的困惑 拿出来请高手指导一下 一下是我写的测试代码

    inline void TESTHR( HRESULT _hr ) 
{ if FAILED(_hr) throw(_hr); }
TESTHR(CoInitialize(NULL));
for (int i=0; i<1000000; i++)
{

BSTR br;
MSXML2::IXMLDOMDocumentPtr docPtr;
TESTHR(docPtr.CreateInstance("Msxml2.DOMDocument.3.0"));
docPtr->loadXML(_T("<root><child><father>100</father></child></root>"));
CString strValue = _T("//father");
br = strValue.AllocSysString();
docPtr->selectSingleNode(br);
docPtr.Release();
::SysFreeString(br);
}

CoUninitialize();


如果注释掉::SysFreeString(br);就会发生内存泄露,但是当时找了好久都没有发现这一点要泄露,原因是有关此函数的技术文档中写道
CString str("Hockey is Best!");
BSTR bstr = str.AllocSysString();

// bstr now contains "Hockey is best", and can be
// passed to any OLE function requiring a BSTR.
// Normally, the function receiving the BSTR will
// free the string when it is done using it.

上面提到一般函数接收到bstr会在使用它完以后释放掉 如果按照这样理解的话docPtr->selectSingleNode(br);在selectsingNode执行完以后 br就应该被释放掉了的 why还会出现泄露呢?

...全文
1563 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
WaistCoat10 2010-04-14
  • 打赏
  • 举报
回复
BSTR br;
docPtr->selectSingleNode(br);

br只是个指针,函数里咋能释放呢,这个肯定是你调用者释放啊。
  • 打赏
  • 举报
回复
学习 ...
咔复咔 2010-04-14
  • 打赏
  • 举报
回复
还是没有搞懂 msdn中写的意思是谁调用谁释放

docPtr->selectSingleNode(br)

这里被调用了 应该selectSingleNode是caller 那么就应该这个函数去释放内存嘛
Eleven 2010-04-14
  • 打赏
  • 举报
回复
MSDN的原话:
Commonly, if this string is passed to a COM function as an [in] parameter, then this requires the caller to free the string. This can be done by using SysFreeString, as described in the Windows SDK. For more information, see Allocating and Releasing Memory for a BSTR.
Eleven 2010-04-14
  • 打赏
  • 举报
回复
CString str("Hockey is Best!");
BSTR bstr = str.AllocSysString();
...
使用完成以后:
SysFreeString(bstr);

16,472

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC相关问题讨论
社区管理员
  • 基础类社区
  • Web++
  • encoderlee
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

        VC/MFC社区版块或许是CSDN最“古老”的版块了,记忆之中,与CSDN的年龄几乎差不多。随着时间的推移,MFC技术渐渐的偏离了开发主流,若干年之后的今天,当我们面对着微软的这个经典之笔,内心充满着敬意,那些曾经的记忆,可以说代表着二十年前曾经的辉煌……
        向经典致敬,或许是老一代程序员内心里面难以释怀的感受。互联网大行其道的今天,我们期待着MFC技术能够恢复其曾经的辉煌,或许这个期待会永远成为一种“梦想”,或许一切皆有可能……
        我们希望这个版块可以很好的适配Web时代,期待更好的互联网技术能够使得MFC技术框架得以重现活力,……

试试用AI创作助手写篇文章吧