Search code examples
mfccomado

Release BSTR returned from recordset or not


Got some ADODB code here which retrieves a BSTR from a record set, but Im not sure whether the BSTR should be released with SysFreeString or not. Right now it is and it seems to be working but should you do that yourself?

    BSTR bstr = m_pRecordset->Fields->GetItem ( field )->Value.bstrVal;

    int len = SysStringLen(bstr);

    while (len > 0 && iswspace(bstr[len-1])) len--;

    BSTR newstr = SysAllocStringLen(bstr, len);

    SysFreeString(bstr);
    SysFreeString(newstr);

Solution

  • Your code is wrong. m_pRecordset->Fields->GetItem ( field )->Value returns a VARIANT as _variant_t.

    You should save the object in a temporary variable, access the data and the destructor will do the rest.

    _variant_t val = m_pRecordset->Fields->GetItem ( field )->Value;
    
    int len = SysStringLen(val.bstrVal);
    
    while (len > 0 && iswspace(bstr[len-1])) len--;
    
    BSTR newstr = SysAllocStringLen(val.bstrVal, len);
    ...
    SysFreeString(newstr);
    

    See sample here in the MSDN.

    Also it should be mentioned that it would be better to use CComBSTR or _bstr_t instead of BSTR.