Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

Allocating and Releasing Memory for a BSTR

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:

  • 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 IWebBrowser2::put_StatusText( BSTR bstr );
    
    // shows using the Win32 function 
    // to allocate memory for the string: 
    BSTR bstrStatus = ::SysAllocString( L"Some text" );
    if (bstrStatus == NULL)
       return E_OUTOFMEMORY;
    
    pBrowser->put_StatusText( bstrStatus );
    // Free the string:
    ::SysFreeString( bstrStatus );
    //...
    
  • When you call into a function that returns a BSTR, you must free the string yourself. For example:
    HRESULT IWebBrowser2::get_StatusText( BSTR FAR* pbstr ); 
    //...
    BSTR bstrStatus;
    pBrowser->get_StatusText( &bstrStatus );
    
    // shows using the Win32 function 
    // to freee the memory for the string: 
    ::SysFreeString( bstrStatus );
    
  • 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:
    // Example shows using MFC's 
    // CString::AllocSysString
    
    //...
    HRESULT CMyClass::get_StatusText( BSTR * pbstr )
    {
    
       try
       {
          //m_str is a CString in your class
          *pbstr = m_str.AllocSysString( );
          }
       catch (...)
       {
          return E_OUTOFMEMORY;
       }
    
    // The client is now responsible for freeing pbstr.
    return( S_OK );
    }
    //...
    

See Also

Strings | CString::AllocSysString | SysAllocString | SysFreeString

Show:
© 2015 Microsoft