0

The following code behaves fine on my mac but on my linux, it results in segmentation fault.

std::list<sock>::iterator iter;
for(iter = sock_list.begin(); iter != sock_list.end(); ++iter) {
    if ((*iter).fd == param1) {
        sock_list.erase(iter);
    }
}

After searching a bit, I found out that this makes it work on my linux too by adding -- at line 4.

std::list<sock>::iterator iter;
for(iter = sock_list.begin(); iter != sock_list.end(); ++iter) {
    if ((*iter).fd == param1) {
        sock_list.erase(iter--);
    }
}

Although I made it work, I'm still curious why they behave differently. Both have gcc 5.x and c++ 11.

  • The real solution is to use [std::list::remove_if](http://en.cppreference.com/w/cpp/container/list/remove). – juanchopanza Oct 30 '16 at 08:53
  • Thank you for helping me out, and I would definitely use your suggestion to fix my code. But the real question is why they would behave differently on osx and linux. – Jason Lee Oct 30 '16 at 08:58
  • @juanchopanza The post which this is marked as a duplicate doesn't seem to state why the behave differently which was question. – Koga Oct 30 '16 at 08:58
  • @Koga It should be enough to read the chosen answer. Bugs that cause undefined behaviour manifest themselves differently in different circumstances. – juanchopanza Oct 30 '16 at 09:07
  • fyi: _"References and iterators to the erased elements are invalidated. Other references and iterators are not affected."_ So undefined behaviour. – Richard Critten Oct 30 '16 at 09:09
  • Thank you! I guess I would have be careful not to cause undefined behavior in the future. – Jason Lee Oct 30 '16 at 09:52

0 Answers0