FAQ 34.16 What types of errors occur due to reference counting?

graphics/new_icon.gif

Reference counting is a powerful mechanism, but it can lead to errors that are extremely hard to detect.

First, a caller might call AddRef too often or forget to call Release. In this case, there is a memory leak since the COM object never knows when to destroy itself.

Second, a caller might call Release too often. In this case, the reference count of the COM object is reduced to zero prematurely, and the COM object destroys itself leaving a dangling pointer since other callers have interface pointers to the COM object.

Reference counting is made more complicated by performance optimizations. For example, sometimes it is not necessary to call AddRef and Release for a temporary interface pointer if it is going to be created and destroyed within the lifetime of another interface pointer. This sort of optimization creates a dependency between the two interface pointers, and in the future it can become the source of a reference counting error if some invariant associated with the dependency changes.

None of this should be a surprise to C++ programmers. After all, C++ programmers have to deal with the same conditions in C++ programs if the calls to new and delete are not properly coordinated. Forgetting to call delete results in memory leaks and calling delete prematurely results in dangling pointers.

However, the situation in COM is more insidious since COM components can be running in different processes than the ones their callers are running in. For example, a memory leak caused by a caller running in one process may result in a server process continuing to run when it should have shut down, thus consuming operating system resources as well as memory resources. Or worse, a bug in one caller can release a server process prematurely, causing it to shut down while it is still being used by other callers.

Note that Distributed COM (see FAQs 34.39, 34.40) has a security option that performs callbacks to the client to authenticate distributed reference count calls, ensuring that objects are not released maliciously.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net