Skip to content

Commit c709d2a

Browse files
Make sure to properly untrack gc objects before freeing them (#4461)
* Make sure to properly untrack gc objects before freeing them * style: pre-commit fixes * Fix lint * Add comment about where the original track comes from Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent e53d58a commit c709d2a

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

include/pybind11/detail/class.h

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -445,9 +445,17 @@ inline void clear_instance(PyObject *self) {
445445
/// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
446446
/// to destroy the C++ object itself, while the rest is Python bookkeeping.
447447
extern "C" inline void pybind11_object_dealloc(PyObject *self) {
448+
auto *type = Py_TYPE(self);
449+
450+
// If this is a GC tracked object, untrack it first
451+
// Note that the track call is implicitly done by the
452+
// default tp_alloc, which we never override.
453+
if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
454+
PyObject_GC_UnTrack(self);
455+
}
456+
448457
clear_instance(self);
449458

450-
auto *type = Py_TYPE(self);
451459
type->tp_free(self);
452460

453461
#if PY_VERSION_HEX < 0x03080000

0 commit comments

Comments
 (0)