BSTR memory leak in atldbsch.h - what to do?

时间:2015-06-26 10:21:38

标签: c++ memory-leaks

I am running Deleaker application to find and fix memory leaks in an application. Now, it finds a lot of BSTR leaks with roots in the Open()-function of the Microsoft CRestrictions class (atldbsch.h file).

If one looks there one can notice that it takes 7 LPCTSTR parameters, which are then used like this:

pVariant = m_pvarRestrictions + 1;
.
.
pVariant->bstrVal = ::SysAllocString(T2COLE_EX_DEF(lpszParam1));

This is done for all seven such parameters (where the number 1 is increased every time).

The destructor is simply doing

delete[] m_pvarRestrictions;

but the BSTRs allocated via ::SysAllocString() are never freed though via calls to ::SysFreeStr()

Am I missing something or is there a leak, and in that case how should it be handled in this case?

3 个答案:

答案 0 :(得分:1)

检查代码之后我会说没有泄漏因为m_pvarRestrictions是指向CComVariant数组的指针,并且这个数组是通过delete []删除的,所以每个CComVariant都会调用析构函数。 CComVariant :: ~CComVariant()调用VariantClear,如果此VARIANT包含它,它本身将释放BSTR。

然后我检查了Deleaker(版本3.0.66.0)如何与CComVariant一起使用,这里是我的代码:

int _tmain(int argc, _TCHAR* argv[])
{
    CComVariant* v = new CComVariant(L"123");
    delete v;

    return 0;
}

没有泄漏。可能你已经尝试过旧版的Deleaker。

如果我删除了删除v,那么我会看到两个泄漏:堆内存和BSTR。

答案 1 :(得分:0)

根据https://github.com/dpalma/sge/blob/master/3rdparty/atl/atldbsch.hm_pvarRestrictions被定义为ATL::CComVariant *,因此ATL::CComVariant析构函数应该清理BSTR变体(代码正确设置) vtVT_BSTR)。也就是说,CComVariant析构函数调用调用CComVariant::Clear的{​​{1}}。

因此,这里不应该有内存泄漏 - 代码看起来是正确的。这可能是Deleaker在检测到这种模式时遇到问题的一个问题。

答案 2 :(得分:0)

您确定将pVariant类型也设置为VT_BSTR。这未在代码中显示。如果您未设置类型,则会导致泄漏。

如果pVariant实际上是指向CComVariant的指针,则此代码应该起作用:

*pVariant = T2COLE_EX_DEF(lpszParam1);

在这种情况下,VT_BSTR类型已设置,销毁将清除变体。