title: segmentation fault/ error reading variable - c++ list
body: <p>I have a segmentation fault I can't understand.
  This is the code:</p>
  
  <pre><code>void RemoveDuplicates(list&lt;int&gt;&amp; _list)
  {
      set&lt;int&gt; uniqueElements;
      list&lt;int&gt;::iterator iter = _list.begin();
      list&lt;int&gt;::iterator next;
      pair&lt;set&lt;int&gt;::iterator, bool&gt; res;
  
      while (iter != _list.end())
      {
          res = uniqueElements.insert(*iter);
          if (!res.second)
          {
              next = ++iter;
              _list.erase(iter);
              iter = next;
              continue;
          }
          iter++;
      }
  }
  </code></pre>
  
  <p>and a test for the function (in a separate file):</p>
  
  <pre><code>#include &lt;list&gt;
  #include &lt;iostream&gt;
  #include "lists.h"
  
  using namespace std;
  
  int main()
  {
      list&lt;int&gt; list;
      list.push_front(12);
      list.push_front(7);
      list.push_front(2);
      list.push_front(9);
      list.push_front(12);
      list.push_front(12);
      list.push_front(19);
  
      RemoveDuplicates(list);
      cout &lt;&lt; list.size() &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>The segmentation fault occurs at curtain iteration of the while loop that looks quite random to me. When accessing the 5th element in the list (the one with the value 2) in the following line:</p>
  
  <pre><code>res = uniqueElements.insert(*iter);
  </code></pre>
  
  <p>The problem is accessing *iter.
  When I run it through gdb (on g++), I print the *iter each loop (gdb shows the address of the element and its value), and then when I get to the 5th one, it says 'error reading variable'.</p>
  
  <p>As for the <a href="https://stackoverflow.com/questions/596162/can-you-remove-elements-from-a-stdlist-while-iterating-through-it">duplicate</a>
  I think I understand the logic of removing a node from a list, but I still have the problem.
  The ++iter was changed from iter++ (probably wrongly) as an attempt to solve the problem.
  I changed it back to </p>
  
  <pre><code>next = iter++;
  </code></pre>
  
  <p>and I am getting the following error: 
  invalid pointer
  program received signal SIGABRT, Aborted</p>