When you create BSTRs and pass them between COM objects, you must take care in treating the memory they use in order to avoid memory leaks. When a BSTR stays within an interface, you must free its memory when you are done with it. However, when a BSTR passes out of an interface, the receiving object takes responsibility for its memory management.
In general, the rules for allocating and releasing memory allocated for BSTRs are as follows:
1. When you call into a function that expects a BSTR argument, you must allocate the memory for the BSTR before the call and release it afterwards. For example:
HRESULT CMyWebBrowser::put_StatusText(BSTR bstr);
// shows using the Win32 function<br />// to allocate memory for the string:<br />BSTR bstrStatus = ::SysAllocString(L"Some text");<br />if (bstrStatus != NULL)<br />{<br /> pBrowser->put_StatusText(bstrStatus);<br /> // Free the string:<br /> ::SysFreeString(bstrStatus);<br />}
2. When you call into a function that returns a BSTR, you must free the string yourself. For example:
HRESULT CMyWebBrowser::get_StatusText(BSTR* pbstr);
BSTR bstrStatus;<br />pBrowser->get_StatusText(&bstrStatus);<br />// shows using the Win32 function<br />// to free the memory for the string:<br />::SysFreeString(bstrStatus);
3. When you implement a function that returns a BSTR, allocate the string but do not free it. The receiving the function releases the memory. For example:
HRESULT CMyClass::get_StatusText(BSTR* pbstr)<br />{<br /> try<br /> {<br /> //m_str is a CString in your class<br /> *pbstr = m_str.AllocSysString();<br /> }<br /> catch (...)<br /> {<br /> return E_OUTOFMEMORY;<br /> }<br /> // The client is now responsible for freeing pbstr.<br /> return(S_OK);<br />}
http://msdn.microsoft.com/en-us/library/xda6xzx7.aspx