title: Thread Local storage getting corrupted after Access Violation Exception
body: <p>I have some data stored in thread local storage. Basically I have a per thread some kind of attributes stored in TLS. In the TLS we put the custom class object instance CMyAttributes*.</p>
  
  <p>This is an reference counted attributes holder</p>
  
  <p>As an example:</p>
  
  <pre><code>CMyAttributes* CMyAttributes::GetInstance()
  {
     ThreadStorage&amp; tls = GetThreadLocalStorage();
     CMyAttributes* pMyAttributes = reinterpret_cast&lt;CMyAttributes*&gt;(tls.Get());
     if (pMyAttributes == nullptr)
     {
        pMyAttributes = new CMyAttributes();
        pMyAttributes-&gt;AddRef();
        tls.Set(pMyAttributes);
     }
     pMyAttributes-&gt;AddRef();
     return pMyAttributes;
  }
  </code></pre>
  
  <p>Overridden the AddRef and Release. This class is reference counted. In the release when the object being destroyed we clear the TLS by calling tls.Set(nullptr).</p>
  
  <p>Now the issue that we are facing is that when there is an access violation exception we see that the thread local storage is getting corrupted. That is when we invoke the GetInstance call we see that the TLS has garbage values and the pMyAttributes is not null and the Addref crashes.</p>
  
  <p>We could not figure out what is causing the corruption. Any suggestions on debugging this kind of problem.</p>