Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Lib/test/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import sys
import unittest
import warnings
import weakref
from re import Scanner
from weakref import proxy

Expand Down Expand Up @@ -1705,6 +1706,27 @@ def test_finditer(self):
self.assertEqual([item.group(0) for item in iter],
["::", "::"])

def test_finditer_gc(self):
class Text(str):
pass

class Buffer(bytearray):
pass

text = Text('a')
text.iterator = re.finditer('a', text)
ref = weakref.ref(text)
del text
gc_collect()
self.assertIsNone(ref())

buffer = Buffer(b'a')
buffer.iterator = re.finditer(b'a', buffer)
ref = weakref.ref(buffer)
del buffer
gc_collect()
self.assertIsNone(ref())

def test_bug_926075(self):
self.assertIsNot(re.compile('bug_926075'),
re.compile(b'bug_926075'))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a memory leak in :func:`re.finditer` and regular expression scanners when
their input participates in a reference cycle.
7 changes: 6 additions & 1 deletion Modules/_sre/sre.c
Original file line number Diff line number Diff line change
Expand Up @@ -2813,14 +2813,19 @@ scanner_traverse(PyObject *op, visitproc visit, void *arg)
ScannerObject *self = _ScannerObject_CAST(op);
Py_VISIT(Py_TYPE(self));
Py_VISIT(self->pattern);
Py_VISIT(self->state.string);
Py_VISIT(self->state.buffer.obj);
return 0;
}

static int
scanner_clear(PyObject *op)
{
ScannerObject *self = _ScannerObject_CAST(op);
self->state.start = NULL;
Py_CLEAR(self->pattern);
Py_CLEAR(self->state.string);
PyBuffer_Release(&self->state.buffer);
return 0;
}

Expand All @@ -2830,8 +2835,8 @@ scanner_dealloc(PyObject *self)
PyTypeObject *tp = Py_TYPE(self);
PyObject_GC_UnTrack(self);
ScannerObject *scanner = _ScannerObject_CAST(self);
state_fini(&scanner->state);
(void)scanner_clear(self);
state_fini(&scanner->state);
tp->tp_free(self);
Py_DECREF(tp);
}
Expand Down
Loading