【问题标题】:Invalid pointer operation when freeing TStreamAdapter释放 TStreamAdapter 时指针操作无效
【发布时间】:2019-05-13 13:41:15
【问题描述】:

谁能解释一下为什么我在尝试删除TStreamAdapter 时会收到“无效的指针操作”?或者...如何从TStreamAdapter 中正确释放内存?如果我删除了delete,它会起作用,但这会导致内存泄漏。即使我使用 boost::scoped_ptr 它也会失败并出现同样的错误。

注意:我也尝试使用 soOwned 值初始化 TStreamAdapter,同样的错误。

代码:

HRESULT LoadFromStr(TWebBrowser* WB, const UnicodeString& HTML)
{
if (!WB->Document)
    {
    WB->Navigate("about:blank");
    while (!WB->Document) { Application->ProcessMessages(); }
    }

DelphiInterface<IHTMLDocument2> diDoc = WB->Document;

if (diDoc)
    {
    boost::scoped_ptr<TMemoryStream> ms(new TMemoryStream);

        {
        boost::scoped_ptr<TStringList> sl(new TStringList);
        sl->Text = HTML;
        sl->SaveToStream(ms.get(), TEncoding::Unicode);
        ms->Position = 0;
        }

    DelphiInterface<IPersistStreamInit> diPSI;

    if (SUCCEEDED(diDoc->QueryInterface(IID_IPersistStreamInit, (void**)&diPSI)) && diPSI)
        {
        TStreamAdapter* sa = new TStreamAdapter(ms.get(), soReference);
        diPSI->Load(*sa);
        delete sa;  // <-- invalid pointer operation here???

        // UPDATED (solution) - instead of the above!!!
        // DelphiInterface<IStream> sa(*(new TStreamAdapter(ms.get(), soReference)));
        // diPSI->Load(sa);
        // DelphiInterface is automatically freed on function end


        return S_OK;
        }
    }

return E_FAIL;
}

更新:我在这里找到了解决方案 - http://www.cyberforum.ru/cpp-builder/thread743255.html

解决方案是使用 _di_IStream sa(*(new TStreamAdapter(ms.get(), soReference))); 或者... DelphiInterface&lt;IStream&gt; sa(*(new TStreamAdapter(ms.get(), soReference)));

因为一旦超出范围,它将自动释放 IStream。至少应该 - 这里可能存在内存泄漏吗? (CodeGuard 没有检测到任何内存泄漏)。

【问题讨论】:

    标签: com c++builder


    【解决方案1】:

    TStreamAdapterTInterfacedObject 的后代,它实现了引用计数语义。你根本不应该delete它,当它不再被任何人引用时,你需要让引用计数释放对象。

    使用_di_IStream(它只是DelphiInterface&lt;IStream&gt; 的别名)是使用智能指针实现自动化的正确方法。 TComInterface&lt;IStream&gt;CComPtr&lt;IStream&gt; 也可以。

    【讨论】:

    • 很高兴是你做出了回复 - 谢谢 - 因为我希望这个 delphigroups.info/3/1/174612.html 也能得到纠正(猜猜删除 TStreamAdapter* 的想法是从哪里来的)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多