Skip to content

Commit e63dfde

Browse files
committed
Fix a memory leak when creating Python3 modules.
1 parent dc9006d commit e63dfde

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

include/pybind11/pybind11.h

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -794,11 +794,16 @@ class module : public object {
794794
explicit module(const char *name, const char *doc = nullptr) {
795795
if (!options::show_user_defined_docstrings()) doc = nullptr;
796796
#if PY_MAJOR_VERSION >= 3
797-
PyModuleDef *def = new PyModuleDef();
797+
PyModuleDef *def = PyMem_New(PyModuleDef, 1);
798798
std::memset(def, 0, sizeof(PyModuleDef));
799799
def->m_name = name;
800800
def->m_doc = doc;
801801
def->m_size = -1;
802+
def->m_free = [](void* module ) {
803+
if (module != nullptr) {
804+
Py_XDECREF(PyModule_GetDef((PyObject*) module));
805+
}
806+
};
802807
Py_INCREF(def);
803808
m_ptr = PyModule_Create(def);
804809
#else

0 commit comments

Comments
 (0)