COM, BSTR or _bstr_t is leaking memory

COM, BSTR or _bstr_t is leaking memory. That was my first thought when I saw increasing number in Task Manager under memory colon for the process I am developing.

Searching Google for quick answer I found famous Microsoft employee and blogger Larry Osterman’s blog post about Hey, why am I leaking all my BSTR’s? He describes OLE caching of BSTR objects and tool called UMDH. OLE caching is not my case, however UMDH may be useful is you are able to figure out what to do.

Another link I found is from 1999 (VS6) Implementing a Simple MFC Client for an ATL Server. They have notes about memory leaks all over the place. Particularly interesting are two examples I have copied below.

Without leak:
//Update static text with new value
BSTR tmpBStr;
 
m_pObject1->get_ObjectString(&tmpBStr);
_bstr_t tmpbstr(tmpBStr, FALSE); //necessary to avoid a memory leak
 
SetDlgItemText(IDC_CURPROPVAL, tmpbstr);

With leak:
//Update static text with new value
BSTR tmpBStr;
 
m_pObject1->get_ObjectString(&tmpBStr);
_bstr_t tmpbstr;
 
tmpbstr= tmpBStr; //Caution: Memory leak occurs
SetDlgItemText(IDC_CURPROPVAL, tmpbstr);

And explanation:

The leak occurs when the tmpbstr variable is initialized. A call to SysAllocString (reference available in the Component Services section of the Platform SDK) is automatically made when creating the tmpbstr variable. This new allocation is never freed later, resulting in a memory leak. Using this version of the _bstr_t constructor avoids the issue by attaching the BSTR object to tmpbstr without a call to SysAllocString. For more information on this issue, see _bstr_t::_bstr_t (reference available in the C++ Language Reference section of the Visual C++ Documentation).

The problem is that explanation is wrong. My speculation: Most probably one person (senior programmer?) found memory leak in documentation, fixed it and told another person (junior programmer?) to update documentation. And that second person got it wrong. First: _bstr_t constructor _bstr_t::_bstr_t() does not allocate memory. Second: if it were allocating, then it would be freed, see the code below:
_bstr_t& _bstr_t::operator=(const wchar_t* s)
{
    if (s == NULL || ...)
    {
        _Free();
        m_Data = new Data_t(s);

And yes, _Free does exactly that. It frees m_Data if it contains something, in our case as I noted above, it points to 0x00000000;

operator=(const wchar_t* s) is exactly what is called in my case – Unicode compile.

Again, the code in Microsoft article leaks memory as comment says, but it does not leak as it is described. It leaks because memory allocated by m_pObject1->get_ObjectString is not freed.

In the end I found my memory leak. It was similar problem, I needed to call _bstr_t constructor with FALSE as second argument. From MSDN: If false, the bstr argument is attached to the new object without making a copy by calling SysAllocString.

So be careful playing with BSTRs.

2011 links no. 3

Interview With Sacha Barber in The Code Project.

The ABA problem occurs during synchronization, when a location is read twice, has the same value for both reads, and “value is the same” is used to indicate “nothing has changed”. However, another thread can execute between the two reads and change the value, do other work, then change the value back, thus fooling the first thread in to thinking “nothing has changed” even though the second thread did work that violates that assumption.

An Idiot’s Guide to C++ Templates by Ajay Vijayvargiya from The Code Project.

C++0x Finally Becomes a Standard discussed in Slashdot.

What is Cloud Programming and why should we care By GanesanSenthilvel at The Code Project.

Interesting discussion in StackOverflow about Creating a memory leak with Java.

Why is subtracting two times (in 1927) is giving a strange result? or in Shanghai at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. From StackOverflow.

$300M To Save 6 Milliseconds in high frequency trading discussed at Slashdot.

Age bias in IT: Some consider it IT’s dirty little secret, or even IT’s big open secret – from computerworld.com by Tam Harbert.

Am I Too Old To Learn New Programming Languages? from Slashdot and Become a Good Programmer in Six Really Hard Steps from ApochPiQ in GameDev.net.

InfoWorld writes about The nine circles of IT hell by Dan Tynan.

Biggest Mistakes in Web Design 1995-2015 from webpagesthatsuck.com.

From glyph recognition to augmented reality with video demos and source code By Andrew Kirillov in The Code Project.

Introduction to Google App Inventor by VinayakIyer from The Code Project.

Guide to Image Composition with Win32 MsImg32.dll By Paul Watt from The Code Project.

JavaScript Jargon (Coming to JavaScript from C#) By Jonathan Cardy.

Learn to code: Codecademy is the easiest way to learn how to code. It’s interactive, fun, and you can do it with your friends.

Minimalist Coding Guidelines By gggustafson.

Penrose Tiling in Obfuscated Python or Who says you can’t write obfuscated Python? from Jeff Preshing.

Learn Perl in about 2 hours 30 minutes By Sam Hughes.

PowerShell is powerful but can it handle gaming? PowerShell Falling Blocks By Lasse W.

Sudoku solver via a webcam: A nice computer vision application with source code from Bojan Banko.

Windows API: Slim Reader/Writer (SRW) Locks from MSDN (available from Vista and Server 2008).

The Five Levels of ISP Evil from Dane Jasper.

spin.js – cool open source JavaScript spinner hosted in GitHub.

Starting up inside the box (Vista and above) from Raymond Chen.

Stuxnet Malware Analysis Paper By AmrThabet. This article will focus on Stuxnet’s windows infection methods and spreading methods.

The Power of Rooting on Android By David Magnotti.

The Principles of Good Programming by Christopher Diggins.

.NET ThreadPool vs. Tasks by Paul Stovell.

Why does creating a shortcut to a file change its last-modified time… sometimes? from Raymond Chen.

Writing a Multiplayer Game (in WPF) By Paulo Zemek. This article will explain some concepts of game development and how to apply and adapt them for multiplayer development.

.NET Framework 2.0 is not installed on Windows 8 Developer Preview by default

.NET Framework 2.0 is not installed on Windows 8 Developer Preview by default.

To install it, go to Control Panel – Programs – Turn Windows features on or off – Check ‘Microsoft .NET Framework 3.5.1’ – OK.

Note, that .NET Framework 2.0 is included into version 3.5.

Below are some screenshots from the installation process.