BUG: GetBlockFormatNames Method Memory Leak in Afxhtml.h (315482)



The information in this article applies to:

  • Microsoft Visual C++ .NET (2002)
  • Microsoft Visual C++ .NET (2003)

This article was previously published under Q315482

SYMPTOMS

When you call the GetBlockFormatNames method, the method causes memory leaks.

CAUSE

The GetBlockFormatNames function in Afxhtml.h calls SafeArrayGetElement to allocate memory for the BSTR variable bstrElem. However, there is no corresponding SysFreeString call to release the memory. Also, the SAFEARRAY *psa is not released properly.

RESOLUTION

To work around this issue, do one of the following:
  • Change the GetBlockFormatNames method in the Afxhtml.h header file to free the BSTR variable bstrElem after the method accesses the variable. Call SafeArrayDestroy to release SAFEARRAY *psa.

    -or-
  • Do not call the GetBlockFormatNames method. Instead, copy and paste the following sample code into your code. The sample code frees the BSTR variable bstrElem after the method accesses the variable, and then calls SafeArrayDestroy to release SAFEARRAY *psa.
HRESULT GetBlockFormatNames(CStringArray &sa) const
{
    CComVariant vaRet;
    HRESULT hr = E_FAIL;
    long lStatus = QueryStatus(IDM_GETBLOCKFMTS);
    if (lStatus & OLECMDF_ENABLED || lStatus & OLECMDF_LATCHED)
    {
        if (S_OK == ExecCommand(IDM_GETBLOCKFMTS, OLECMDEXECOPT_DODEFAULT, NULL, &vaRet))
        {						 
            if(vaRet.vt & VT_ARRAY)
            {
                 USES_CONVERSION;
                 SAFEARRAY *psa = vaRet.parray;
				
                 long lBound = 0,uBound = 0;
                 if(S_OK == SafeArrayGetLBound(psa,1,&lBound) &&
                     S_OK == SafeArrayGetUBound(psa,1,&uBound) )
                 {
                     for(long i=lBound; i<uBound; i++)
                     {	
                         CComBSTR bstrElem;
                         if( (S_OK == SafeArrayGetElement(psa, &i, &bstrElem)) )
                             sa.Add(CString(OLE2T(bstrElem)));
                     }
                     SafeArrayDestroy(psa); 		//Release psa.

                     hr = S_OK;
                 }
            }
        }
    }

    if (vaRet.vt == VT_ERROR) {
        hr = V_ERROR(&vaRet);
    }

    return hr;
}
				

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

Modification Type:MinorLast Reviewed:5/28/2003
Keywords:kbbug kbfix KB315482