bpo-42015: Reorder dereferencing calls in meth_dealloc, to make sure m_self is kept alive long enough (GH-22670)
diff --git a/Objects/methodobject.c b/Objects/methodobject.c
index 5659f21..7b43041 100644
--- a/Objects/methodobject.c
+++ b/Objects/methodobject.c
@@ -164,9 +164,11 @@
if (m->m_weakreflist != NULL) {
PyObject_ClearWeakRefs((PyObject*) m);
}
+ // Dereference class before m_self: PyCFunction_GET_CLASS accesses
+ // PyMethodDef m_ml, which could be kept alive by m_self
+ Py_XDECREF(PyCFunction_GET_CLASS(m));
Py_XDECREF(m->m_self);
Py_XDECREF(m->m_module);
- Py_XDECREF(PyCFunction_GET_CLASS(m));
PyObject_GC_Del(m);
}
@@ -243,9 +245,9 @@
static int
meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg)
{
+ Py_VISIT(PyCFunction_GET_CLASS(m));
Py_VISIT(m->m_self);
Py_VISIT(m->m_module);
- Py_VISIT(PyCFunction_GET_CLASS(m));
return 0;
}