8000 gh-94207: Fix struct module leak by mdickinson · Pull Request #94239 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-94207: Fix struct module leak #94239

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 3 commits into from
Jun 25, 2022
Merged
Changes from 1 commit
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
Next Next commit
Make _struct.Struct a GC type
This fixes a memory leak in the _struct module, where as soon
as a Struct object is stored in the cache, there's a cycle from
the _struct module to the cache to Struct objects to the Struct
type back to the module. If _struct.Struct is not gc-tracked, that
cycle is never collected.
  • Loading branch information
mdickinson committed Jun 24, 2022
commit cc930e1945545b1ba47bd2bae473eeb8c2fe0e32
22 changes: 20 additions & 2 deletions Modules/_struct.c
Original file line number Diff line number Diff line change
Expand Up @@ -1496,10 +1496,26 @@ Struct___init___impl(PyStructObject *self, PyObject *format)
return ret;
}

static int
s_clear(PyStructObject *s)
{
Py_CLEAR(s->s_format);
return 0;
}

static int
s_traverse(PyStructObject *s, visitproc visit, void *arg)
{
Py_VISIT(Py_TYPE(s));
Py_VISIT(s->s_format);
return 0;
}

static void
s_dealloc(PyStructObject *s)
{
PyTypeObject *tp = Py_TYPE(s);
PyObject_GC_UnTrack(s);
if (s->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *)s);
if (s->s_codes != NULL) {
Expand Down Expand Up @@ -2078,21 +2094,23 @@ static PyType_Slot PyStructType_slots[] = {
{Py_tp_getattro, PyObject_GenericGetAttr},
{Py_tp_setattro, PyObject_GenericSetAttr},
{Py_tp_doc, (void*)s__doc__},
{Py_tp_traverse, s_traverse},
{Py_tp_clear, s_clear},
{Py_tp_methods, s_methods},
{Py_tp_members, s_members},
{Py_tp_getset, s_getsetlist},
{Py_tp_init, Struct___init__},
{Py_tp_alloc, PyType_GenericAlloc},
{Py_tp_new, s_new},
{Py_tp_free, PyObject_Del},
{Py_tp_free, PyObject_GC_Del},
{0, 0},
};

static PyType_Spec PyStructType_spec = {
"_struct.Struct",
sizeof(PyStructObject),
0,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,
PyStructType_slots
};

Expand Down
0