{"id":39903,"date":"2004-04-06T07:00:00","date_gmt":"2004-04-06T07:00:00","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/oldnewthing\/2004\/04\/06\/reference-counting-is-hard\/"},"modified":"2004-04-06T07:00:00","modified_gmt":"2004-04-06T07:00:00","slug":"reference-counting-is-hard","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/oldnewthing\/20040406-00\/?p=39903","title":{"rendered":"Reference counting is hard."},"content":{"rendered":"<p>\nOne of the big advantages of managed code is that you don&#8217;t have\nto worry about managing object lifetimes. Here&#8217;s an example of\nsome unmanaged code that tries to manage reference counts and\ndoesn&#8217;t quite get it right.\nEven a seemingly-simple function has a reference-counting bug.\n<\/p>\n<pre>\ntemplate &lt;class T&gt;\nT *SetObject(T **ppt, T *ptNew)\n{\n if (*ppt) (*ppt)-&gt;Release(); \/\/ Out with the old\n *ppt = ptNew; \/\/ In with the new\n if (ptNew) (ptNew)-&gt;AddRef();\n return ptNew;\n}\n<\/pre>\n<p>\nThe point of this function is to take a (pointer to)\na variable that points to one object and replace it with\na pointer to another object.  This is a function that sits\nat the bottom of many &#8220;smart pointer&#8221; classes.  Here&#8217;s\nan example use:\n<\/p>\n<pre>\ntemplate &lt;class T&gt;\nclass SmartPointer {\npublic:\n SmartPointer(T* p = NULL)\n   : m_p(NULL) { *this = p; }\n ~SmartPointer() { *this = NULL; }\n T* operator=(T* p)\n   { return SetObject(&amp;m_p, p); }\n operator T*() { return m_p; }\n T** operator&amp;() { return &amp;m_p; }\nprivate:\n T* m_p;\n};\nvoid Sample(IStream *pstm)\n{\n  SmartPointer&lt;IStream&gt; spstm(pstm);\n  SmartPointer&lt;IStream&gt; spstmT;\n  if (SUCCEEDED(GetBetterStream(&amp;spstmT))) {\n   spstm = spstmT;\n  }\n  ...\n}\n<\/pre>\n<p>\nOh why am I explaining this?  You know how smart pointers work.\n<\/p>\n<p>\nOkay, so the question is, what&#8217;s the bug here?\n<\/p>\n<p>\nStop reading here and don&#8217;t read ahead until you&#8217;ve figured it out\nor you&#8217;re stumped or you&#8217;re just too lazy to think about it.\n<\/p>\n<hr \/>\n<p STYLE=\"height: 20pc\">\n<p>\nThe bug is that the old object is Release()d before the new object\nis AddRef()&#8217;d.  Consider:\n<\/p>\n<pre>\n  SmartPointer&lt;IStream&gt; spstm;\n  CreateStream(&amp;spstm);\n  spstm = spstm;\n<\/pre>\n<p>\nThis assignment statement looks harmless (albeit wasteful).\nBut is it?\n<\/p>\n<p>\nThe &#8220;smart pointer&#8221; is constructed with NULL,\nthen the CreateStream creates a stream and assigns it to\nthe &#8220;smart pointer&#8221;.  The stream&#8217;s reference count is now one.\nNow the assignment statement is executed, which turns into\n<\/p>\n<pre>\n SetObject(&amp;spstm.m_p, spstm.m_p);\n<\/pre>\n<p>\nInside the SetObject function, ppt points tp spstm.m_p, and\npptNew equals the original value of spstm.m_p.\n<\/p>\n<p>\nThe first thing that SetObject does is release the old pointer,\nwhich now drops the reference count of the stream to zero.\n<strong>This destroys the stream object<\/strong>.\nThen the ptNew parameter (which now points to a freed object)\nis assigned to spstm.m_p, and finally the ptNew pointer\n(which still points to a freed object) is AddRef()d.\nOops, we&#8217;re invoking a method on an object that has been freed;\nno good can come of that.\n<\/p>\n<p>\nIf you&#8217;re lucky, the AddRef() call crashes brilliantly so\nyou can debug the crash and see your error.\nIf you&#8217;re not lucky (and you&#8217;re usually not lucky),\nthe AddRef() call interprets the freed memory as if it were\nstill valid and increments a reference count somewhere inside\nthat block of memory. Congratulations, you&#8217;ve now corrupted memory.\nIf that&#8217;s not enough to induce a crash (at some unspecified point\nin the future), when the &#8220;smart pointer&#8221;\ngoes out of scope or otherwise changes its referent, the invalid\nm_p pointer will be Release()d, corrupting memory yet another time.\n<\/p>\n<p>\nThis is why &#8220;smart pointer&#8221; assignment functions must AddRef() the\nincoming pointer before Release()ing the old pointer.<\/p>\n<pre>\ntemplate &lt;class T&gt;\nT *SetObject(T **ppt, T *ptNew)\n{\n if (ptNew) (ptNew)-&gt;AddRef();\n if (*ppt) (*ppt)-&gt;Release();\n *ppt = ptNew;\n return ptNew;\n}\n<\/pre>\n<p>\nIf you look at the source code for\n<a HREF=\"http:\/\/msdn.microsoft.com\/library\/en-us\/vclib\/html\/vclrfAtlComPtrAssign.asp\">\nthe ATL function AtlComPtrAssign<\/a>,\nyou can see that it exactly matches the above (corrected) function.\n<\/p>\n<p>\n[Raymond is currently on vacation; this message was pre-recorded.]<\/p>\n","protected":false},"excerpt":{"rendered":"<p>One of the big advantages of managed code is that you don&#8217;t have to worry about managing object lifetimes. Here&#8217;s an example of some unmanaged code that tries to manage reference counts and doesn&#8217;t quite get it right. Even a seemingly-simple function has a reference-counting bug. template &lt;class T&gt; T *SetObject(T **ppt, T *ptNew) { [&hellip;]<\/p>\n","protected":false},"author":1069,"featured_media":111744,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[1],"tags":[25],"class_list":["post-39903","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-oldnewthing","tag-code"],"acf":[],"blog_post_summary":"<p>One of the big advantages of managed code is that you don&#8217;t have to worry about managing object lifetimes. Here&#8217;s an example of some unmanaged code that tries to manage reference counts and doesn&#8217;t quite get it right. Even a seemingly-simple function has a reference-counting bug. template &lt;class T&gt; T *SetObject(T **ppt, T *ptNew) { [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/39903","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/users\/1069"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/comments?post=39903"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/posts\/39903\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media\/111744"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/media?parent=39903"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/categories?post=39903"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/oldnewthing\/wp-json\/wp\/v2\/tags?post=39903"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}