Skip to content

GH-89988: Fix memory leak in pickle.Pickler dispatch_table lookup #94298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 28, 2022
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
23 changes: 23 additions & 0 deletions Lib/test/test_pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,29 @@ def persistent_id(obj):
return obj
check(PersPickler)

@support.cpython_only
def test_custom_pickler_dispatch_table_memleak(self):
# See https://github.com/python/cpython/issues/89988

class Pickler(self.pickler):
def __init__(self, *args, **kwargs):
self.dispatch_table = table
super().__init__(*args, **kwargs)

class DispatchTable:
pass

table = DispatchTable()
pickler = Pickler(io.BytesIO())
self.assertIs(pickler.dispatch_table, table)
table_ref = weakref.ref(table)
self.assertIsNotNone(table_ref())
del pickler
del table
support.gc_collect()
self.assertIsNone(table_ref())


@support.cpython_only
def test_unpickler_reference_cycle(self):
def check(Unpickler):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix memory leak in :class:`pickle.Pickler` when looking up :attr:`dispatch_table`. Patch by Kumar Aditya.
4 changes: 3 additions & 1 deletion Modules/_pickle.c
Original file line number Diff line number Diff line change
Expand Up @@ -4761,7 +4761,9 @@ _pickle_Pickler___init___impl(PicklerObject *self, PyObject *file,
{
return -1;
}

if (self->dispatch_table != NULL) {
return 0;
}
if (_PyObject_LookupAttr((PyObject *)self, &_Py_ID(dispatch_table),
&self->dispatch_table) < 0) {
return -1;
Expand Down