From a3626bc5bddf9bf43f33060f4ea1a99f25e0c7f1 Mon Sep 17 00:00:00 2001
From: Raymond Hettinger <python@rcn.com>
Date: Wed, 15 Jul 2015 23:50:14 -0700
Subject: [PATCH] Issue #24583: Fix crash when set is mutated while being
 updated.

---
 Lib/test/test_set.py | 13 +++++++++++++
 Misc/NEWS            |  2 ++
 Objects/setobject.c  |  3 ++-
 3 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py
index 9f96f875c5d..54de508a832 100644
--- a/Lib/test/test_set.py
+++ b/Lib/test/test_set.py
@@ -1742,6 +1742,19 @@ class TestWeirdBugs(unittest.TestCase):
         s.update(range(100))
         list(si)
 
+    def test_merge_and_mutate(self):
+        class X:
+            def __hash__(self):
+                return hash(0)
+            def __eq__(self, o):
+                other.clear()
+                return False
+
+        other = set()
+        other = {X() for i in range(10)}
+        s = {0}
+        s.update(other)
+
 # Application tests (based on David Eppstein's graph recipes ====================================
 
 def powerset(U):
diff --git a/Misc/NEWS b/Misc/NEWS
index bb7e04d7b87..e1d78ad314a 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,8 @@ Core and Builtins
 
 - Issue #24569: Make PEP 448 dictionary evaluation more consistent.
 
+- Issue #24583: Fix crash when set is mutated while being updated.
+
 - Issue #24407: Fix crash when dict is mutated while being updated.
 
 Library
diff --git a/Objects/setobject.c b/Objects/setobject.c
index d962c1e44a0..704d7e2b2a7 100644
--- a/Objects/setobject.c
+++ b/Objects/setobject.c
@@ -600,7 +600,8 @@ set_merge(PySetObject *so, PyObject *otherset)
     }
 
     /* We can't assure there are no duplicates, so do normal insertions */
-    for (i = 0; i <= other->mask; i++, other_entry++) {
+    for (i = 0; i <= other->mask; i++) {
+        other_entry = &other->table[i];
         key = other_entry->key;
         if (key != NULL && key != dummy) {
             Py_INCREF(key);
-- 
2.30.9