Why would I segfault while removing from a list?
<p>I am trying to remove an object from a list if it meets certain criteria in C++11 and then return true if the object was found:</p>

<pre><code>int x = 178;
typename network_internal_edge_store_type::iterator itr =
    internal_edges.begin();
for (; itr != internal_edges.end(); ++itr) {
  // If edge object found that has this property, then remove it.
  if (itr-&gt;index1() == x || itr-&gt;index2() == x) {
    itr = internal_edges.erase(itr);
    return true;
  }
}
return false;
</code></pre>

<p>However, this segfaults on the line <code>itr = internal_edges.erase(itr);</code>. <code>internal_edges</code> is a list of shared pointers of objects representing edges in a network that I defined above.</p>

<p>At first I thought I was dereferencing an invalid iterator, so I set a breakpoint at that line. To my surprise, the iterator seemed valid when I dereferenced it as a watch expression (<code>*itr</code>).</p>

<p>Then, I thought that the trouble may stem from how the iterator points to a shared pointer, so I tried <code>itr-&gt;reset()</code> before <code>itr = internal_edges.erase(itr);</code>, but the program then segfaults on the line <code>itr-&gt;reset()</code>.</p>

<p>What else could cause this segfault?</p>

<p>Here's more info on the type of <code>internal_edges</code>.</p>

<pre><code>class NetworkInternalEdge;
typedef NetworkInternalEdge network_internal_edge_type;
typedef std::weak_ptr&lt; network_internal_edge_type &gt; network_weak_edge_ptr;
typedef std::shared_ptr&lt; network_internal_edge_type &gt; network_shared_edge_ptr;
typedef std::list&lt; network_shared_edge_ptr &gt; network_internal_edge_store_type;
network_internal_edge_store_type internal_edges;
</code></pre>

<p>== Tracing the error ==</p>

<p>I'm still trying to reproduce this error with a small test case. I also realized that the error relates to the line <code>_M_dispose();</code> (line 147) in shared_ptr_base.h:</p>

<pre><code>      void
  _M_release() noexcept
  {
    // Be race-detector-friendly.  For more info see bits/c++config.
    _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&amp;_M_use_count);
if (__gnu_cxx::__exchange_and_add_dispatch(&amp;_M_use_count, -1) == 1)
  {
        _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&amp;_M_use_count);
    _M_dispose();
    // There must be a memory barrier between dispose() and destroy()
    // to ensure that the effects of dispose() are observed in the
    // thread that runs destroy().
    // See http://gcc.gnu.org/ml/libstdc++/2005-11/msg00136.html
    if (_Mutex_base&lt;_Lp&gt;::_S_need_barriers)
      {
</code></pre>

<p>It seems that something is up with the shared pointers. At the time of erasing, there exist 1 shared and 3 weak pointers that point to <code>**itr</code>. Does that help?</p>
