INFO: OLE Automation BSTR Caching & Finding Memory Leak Sources

ID: Q139071

The information in this article applies to:

SUMMARY

OLE Automation caches the space allocated for BSTR strings. This may cause IMallocSpy to attribute memory leaks to the wrong BSTR user in an application that uses OLE Automation's BSTR strings. The correct source of the leak can be found by disabling OLE Automation's caching by using the debug version of the Oleaut32.dll file and by setting the environment variable OANOCACHE=1 before running the application.

MORE INFORMATION

OLE Automation caches the space allocated for BSTRs. This speeds up the SysAllocString/SysFreeString sequence. However this may cause IMallocSpy to attribute leaks to the wrong memory user because it is not aware of the caching done by OLE automation. For example, if the application allocates a BSTR and frees it, the freed block of memory is put into the BSTR cache by OLE Automation. If the application then allocates another BSTR, it may get the free block from the cache. If the second BSTR allocation is not freed, IMallocSpy will attribute the leak to the first allocation of the BSTR. The correct leak source (the second allocation) can be determined by disabling the BSTR caching done by OLE Automation. This can be done by using the debug version of Oleaut32.dll and by setting environment variable OANOCACHE=1 before running the application.

It is also important to check for leaks at the correct time to prevent false leak reports caused by the IMallocSpy implementation checking for leaks too soon. Users of memory allocated by IMalloc can legitimately hold on to it after OleUninitialize. For example, the OLE Automation BSTR cache is deleted at the Oleaut32.dll file's DLL_PROCESS_DETACH time. This means that checking for leaks immediately after OleUninitialize may cause false reports of memory leaks. A good place to check for memory leaks is in the destructor of a static instance of a class that implements IMallocSpy. The destructor of this static instance is called after the DllMain of each of the DLLs linked by the application is called with DLL_PROCESS_DETACH.

Additional query words: memory leak

Keywords          : LeTwoAto 
Platform          : NT WINDOWS
Issue type        : kbinfo

Last Reviewed: December 11, 1997