简体   繁体   中英

Memory leaks while using CComBstr and system::string

class ATL_NO_VTABLE CMasterStore : 

    public CComObjectRootEx<CComSingleThreadModel>,

    public CComCoClass<CMasterStore, &CLSID_MasterStore>,

    public IDispatchImpl<IMasterStore, &IID_IMasterStore, &LIBID_PSLOGLib>
{

STDMETHODIMP CMasterStore::get_Description(BSTR *pVal)
{
   *pVal = fbstrDescription.Copy();
    return S_OK;
}

STDMETHODIMP CMasterStore::put_Description(BSTR newVal)
{

   //SetDirty();

   fbstrDescription = newVal;

    return S_OK;
}
};

/* masterStore used below is a c# class as define here

public ref class MasterStore { public: property short Code; property String^ Description;*/

IMasterStore* _CurrentMasterStore; //interface

Below line of code is causing memory leak ..

_CurrentMasterStore->put_Description(static_cast<BSTR>(Marshal::StringToBSTR(masterStore->Description).ToPointer()));

If I simply pass string as below, I don't see any memory leaks.

_CurrentMasterRecord->put_Description(L"Test memory leaks");

I am unable to find why it is leaking and how to fix it.

Any help is appreciated.

Thank you very much in advance!!

The StringToBSTR method allocates a BSTR on the system heap for the string and assigns puts the string in the newly allocated BSTR and returns the pointer to the string. Memory has been allocated on the caller's behalf and the caller is responsible for releasing the memory when it is no longer needed (presumably after the call to put_Description)

The second approach probably puts the string in the code as a constant literal so no memory is allocated. BSTRs are typically used when the string is going across a process boundary where as the string literal will not cross the process boundary intact. Also a BSTR is not the same a wide string (L'My string') - see https://social.msdn.microsoft.com/Forums/vstudio/en-US/75a504d1-03b7-4592-8dab-b6897585de6a/bstr-bstrt-sysallocstring-wchar-and-passing-parameters-to-wmi-methods?forum=vcgeneral .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM