title: Yet Another "pointer being freed was not allocated"
body: <p>OK, I'm aware of the tons of posts regarding this error, but I couldn't find one with a simple example and a clear explanation of the issue. Disclaimer: I swear this is not an assignment :) I was just playing around with smart pointers, to figure them out, and this happened.</p>
  
  <pre><code>shared_ptr&lt;string&gt; a = make_shared&lt;string&gt;("This is a string.");
  shared_ptr&lt;string&gt; b = make_shared&lt;string&gt;("This is b string.");
  cout &lt;&lt; a.use_count() &lt;&lt; " " &lt;&lt; b.use_count() &lt;&lt; endl;
  a.reset(b.get());
  cout &lt;&lt; a.use_count() &lt;&lt; " " &lt;&lt; b.use_count() &lt;&lt; endl;
  </code></pre>
  
  <p>After this code, I would expect a to point at b – which is the case – and b getting a use count of 2. Instead, I get the following output:</p>
  
  <pre><code>1 1
  1 1
  </code></pre>
  
  <p>Fair enough, I thought. After all, I'm passing a raw pointer, how the heck is the compiler/runtime supposed to know of its associated control block, right? Right?! (ok, I genuinely expected the compiler to be able to figure this out, but I suppose this is a simple case, and there must be good reasons if this does not happen)</p>
  
  <p>Moving on, I have the following code</p>
  
  <pre><code>cout &lt;&lt; a &lt;&lt; " " &lt;&lt; *a &lt;&lt; endl;
  cout &lt;&lt; b &lt;&lt; " " &lt;&lt; *b &lt;&lt; endl;
  </code></pre>
  
  <p>which nicely prints out</p>
  
  <pre><code>0x7f8f10403288 This is b string.
  0x7f8f10403288 This is b string.
  </code></pre>
  
  <p>OK, this is exactly what I expected: a now points at b. But then, immediately after, I have a return 0 and I get out of the main(), whereas the output shouts out the following</p>
  
  <pre><code>tests(62775,0x7fff7940d000) malloc: *** error for object 0x7f8f10403288: pointer being freed was not allocated
  *** set a breakpoint in malloc_error_break to debug
  </code></pre>
  
  <p>Now I'm confused: which pointer being freed was not allocated, exactly? My money would be on either a or b, since they point at the same thing, naturally they are going out of scope, thus their delete is called twice on the same pointer. Am I right? Am I missing something? Is there something else I should absolutely know?</p>
  
  <p><strong>EDIT</strong> I tried the dumb-pointer equivalent</p>
  
  <pre><code>string* a = new string("This is a string");
  string* b = new string("This is b string");
  
  a = b;
  
  cout &lt;&lt; *a &lt;&lt; endl &lt;&lt; *b &lt;&lt; endl;
  </code></pre>
  
  <p>and the code didn't choke this time. So, is there something special happening around smart pointers?</p>