刚刚开始用ATL写COM组件,遇到RtlSizeHeap问题

本文介绍了一个关于COM组件中使用_bstr_t类型成员变量导致RtlSizeHeap问题的案例。通过详细分析问题产生的原因及解决方案,帮助读者理解如何正确地管理和释放COM对象中的字符串资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚刚开始用ATL写COM组件,遇到RtlSizeHeap,RtlReeHeap问题

去网上Google一下 ATL RtlSizeHeap

www.codguru.com上有位大哥给出了这个

bafraser - As it turns out, I was able to determine why I was getting this RTLSizeHeap problem. Being a novice to COM and ATL, I had a class that stored a string (_bstr_t) value. As you would expect, I had the normal get_ and put_ functions to operate on the member. The problem was, my get_ did not send back a copy of the string held onto by the _bstr_t member that I had set up. All I did was assign it (thinking the operator = function actually makes a copy). Since I was using smart pointers, I had the result of the get_ function assigned to another _bstr_t. The problem...both _bstr_t values were looking at the same memory. So no problem would occur when the first object goes out of scope as the first _bstr_t frees the memory it was holding, but when the second object would go out of scope...bam RtlSizeHeap problem - since the second _bstr_t was still pointing to memory that was now freed. To solve this, my get_ function was changed to:

STDMETHODIMP CSomeClass::get_m_sToTime(BSTR *pVal)
{
AFX_MANAGE_STATE(AfxGetAppModuleState())
if (pVal)
*pVal = bstrtToTime.copy();
return S_OK;
}

Summary - RtlSizeHeap is definitely not lying - Most certainly this error is the result of BSTRs and _bstr_t variables not being handled appropriately. Double and tripple check your code - It took me a long time to find this!

Hope this helps!
Dan

嗯,谢谢Dan,原因大概是某个传出的参数,使用的是栈内存.

找找,果然发现是

STDMETHOD(get_Name)(BSTR * Name)
 {
   if (Name == NULL)
   return E_POINTER;  
  *Name=bstrName=_T("设备树");
  return S_OK;
 }

修改为:

STDMETHOD(get_Name)(BSTR * Name)
 {
  CComBSTR  bstrName(_T("设备树"));
  if (Name == NULL)
   return E_POINTER;  
  *Name=bstrName.Copy();
  return S_OK;
 }

搞定!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值