gpt4 book ai didi

带有 VARIANT/bstrVal 代码的 C++ 泄漏

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:46:15 24 4
gpt4 key购买 nike

泄漏检查器告诉我在以下代码中分配的内存上存在内存泄漏:

// Get the value from the object as a variant.
VARIANT vVal;
VariantInit ( &vVal );
hres = clsObj->Get ( fieldName.c_str(), 0, &vVal, 0, 0 );
if ( FAILED ( hres ) )
{
(... various cleanup / throw stuff ...)
}

// And get it as a wstring.
wstring val ( vVal.bstrVal );

(... do some standard, non-memory leaking stuff with the wstring ...)

// Clean up.
VariantClear ( &vVal );

其中的“clsObj”是一个 IWbemClassObject,它是用于 WMI 内容的 Microsoft 接口(interface)。

分配泄漏内存的特定行是“clsObj->Get”行。泄漏检查器然后报告泄漏本身的更具体代码(即在分配泄漏内存时在堆栈跟踪中进一步),我没有源代码:

(ole32): (filename not available): CoRevokeMallocSpy    
(OLEAUT32): (filename not available): GetErrorInfo
(OLEAUT32): (filename not available): SysAllocStringLen
(OLEAUT32): (filename not available): SysAllocString
(wbemcomn): (filename not available): CVar::SetBSTR
(wbemcomn): (filename not available): CVar::FillVariant
(fastprox): (filename not available): CWbemObject::Get

所以看起来 VARIANT vVal 中的底层 BSTR 被泄露了。但是我正在执行 VariantClear...我还需要做其他事情吗?

也许我在 wstring 构造函数中泄露了它?但如果是这样,我不明白。我认为 bstrVal 本质上只是归结为一个 char 指针(或 wchar 或其他); wstring 构造函数应该只是从该地址复制,就好像它是任何其他指针一样,对吗?

这不像是 wstring 构造函数接管了清除最初由 vVal.bstrVal 指向的内存的责任,就好像它在某个引用计数的 COM 对象上执行 Detach() 一样,是吗?

万一重要,这是在 Visual C++ 6 中。

最佳答案

可能没有泄漏!参见 this article by Microsoft's Larry Osterman on the subject它描述了与您所看到的类似的内容:

I found a bunch of the leaks, and fixed them, but one of the leaks I just couldn't figure out showed up every time we allocated a BSTR object. [...]

Basically, OLE caches all BSTR objects allocated in a process to allow it to pool together strings. As a result, these strings are effectively leaked "on purpose". [...]

Fortunately, there's a way of disabling the BSTR caching, simply set the OANOCACHE environment variable to 1 before launching your application. If your application is a service, then you need to set OANOCACHE as a system environment variable (the bottom set of environment variables) and reboot.

关于带有 VARIANT/bstrVal 代码的 C++ 泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14245378/

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