March 12th, 2015

Under what conditions will the IUnknown::AddRef method return 0?

A customer was debugging their application and discovered that for one of the objects they were using, the IUnknown::Add­Ref method returns 0. How is that possible? That would imply that the object’s reference count was originally negative one?

The return value from IUnknown::Add­Ref is the object reference count by convention, but

This value is intended to be used only for test purposes.

The return value is purely advisory and is not required to be accurate.

For example, if the object is a proxy, it will most likely return the reference count of the local proxy rather than the raw reference count of the original object. Conversely, if you have an object with outstanding proxies, the IUnknown::Add­Ref will count only one reference per proxy, even if the proxies themselves have reference counts greater than one.

The object the customer was using came from MSHTML.DLL, and it so happens that the implementation of IUnknown::Add­Ref used by that component always returns zero. It is technically within their rights to do so.

I don’t know for sure, but I suspect this is done on purpose to avoid applications relying on the exact reference count. Applications are known to do dubious things, such as call IUnknown:­Release in a loop until it says the reference count is zero. Making the objects return a value from IUnknown::Add­Ref that betrays no information about the object’s true reference count may have been a defensive step to prevent applications from making any such dubious dependency.

If you install the debugging version of MSHTML.DLL, then the IUnknown::Add­Ref method will return the reference count. Which makes sense in its own way because the value is intended to be used only when debugging.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments

Discussion are closed.