Skip to content

Commit 5ae8429

Browse files
committed
Fix a memory leak when creating Python3 modules.
1 parent fb910ae commit 5ae8429

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

include/pybind11/pybind11.h

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,11 +795,17 @@ class module : public object {
795795
if (!options::show_user_defined_docstrings()) doc = nullptr;
796796
#if PY_MAJOR_VERSION >= 3
797797
PyModuleDef *def = new PyModuleDef();
798+
// Ensure that Python does not try to delete this.
799+
Py_INCREF(def);
798800
std::memset(def, 0, sizeof(PyModuleDef));
799801
def->m_name = name;
800802
def->m_doc = doc;
801803
def->m_size = -1;
802-
Py_INCREF(def);
804+
def->m_free = [](void* module ) {
805+
if (module != NULL) {
806+
delete PyModule_GetDef((PyObject*) module);
807+
}
808+
};
803809
m_ptr = PyModule_Create(def);
804810
#else
805811
m_ptr = Py_InitModule3(name, nullptr, doc);

0 commit comments

Comments
 (0)