]> granicus.if.org Git - python/commitdiff
Issue #13454: Fix a crash when deleting an iterator created by itertools.tee()
authorSerhiy Storchaka <storchaka@gmail.com>
Fri, 25 Jan 2013 11:19:31 +0000 (13:19 +0200)
committerSerhiy Storchaka <storchaka@gmail.com>
Fri, 25 Jan 2013 11:19:31 +0000 (13:19 +0200)
if all other iterators were very advanced before.

Lib/test/test_itertools.py
Misc/NEWS
Modules/itertoolsmodule.c

index 8cdc597e58bc113d73794042e2e6a50f17e8ffde..66e307da5a9321441557d030673ff6be58386def 100644 (file)
@@ -930,6 +930,14 @@ class TestBasicOps(unittest.TestCase):
         del a
         self.assertRaises(ReferenceError, getattr, p, '__class__')
 
+    # Issue 13454: Crash when deleting backward iterator from tee()
+    def test_tee_del_backward(self):
+        forward, backward = tee(range(20000000))
+        for i in forward:
+            pass
+
+        del backward
+
     def test_StopIteration(self):
         self.assertRaises(StopIteration, next, zip())
 
index 147b57c0cede6ad8aa73595564cffaa952d00d14..4c95a123151e2e00b5b0024ac63c452864a879ea 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -202,6 +202,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #13454: Fix a crash when deleting an iterator created by itertools.tee()
+  if all other iterators were very advanced before.
+
 - Issue #12411: Fix to cgi.parse_multipart to correctly use bytes boundaries
   and bytes data. Patch by Jonas Wagner.
 
index 77e76fe588042df8727ad3e9fb96b2c1405898c6..574eb684ccd5bf8bb5f4d1d3b2968646ecf9f7a1 100644 (file)
@@ -401,14 +401,31 @@ teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg)
     return 0;
 }
 
+static void
+teedataobject_safe_decref(PyObject *obj)
+{
+    while (obj && Py_TYPE(obj) == &teedataobject_type &&
+           Py_REFCNT(obj) == 1) {
+        PyObject *nextlink = ((teedataobject *)obj)->nextlink;
+        ((teedataobject *)obj)->nextlink = NULL;
+        Py_DECREF(obj);
+        obj = nextlink;
+    }
+    Py_XDECREF(obj);
+}
+
 static int
 teedataobject_clear(teedataobject *tdo)
 {
     int i;
+    PyObject *tmp;
+
     Py_CLEAR(tdo->it);
     for (i=0 ; i<tdo->numread ; i++)
         Py_CLEAR(tdo->values[i]);
-    Py_CLEAR(tdo->nextlink);
+    tmp = tdo->nextlink;
+    tdo->nextlink = NULL;
+    teedataobject_safe_decref(tmp);
     return 0;
 }
 
@@ -475,6 +492,8 @@ tee_next(teeobject *to)
 
     if (to->index >= LINKCELLS) {
         link = teedataobject_jumplink(to->dataobj);
+        if (link == NULL)
+            return NULL;
         Py_DECREF(to->dataobj);
         to->dataobj = (teedataobject *)link;
         to->index = 0;