Debugging a memory leak

MRAB python at mrabarnett.plus.com
Fri Oct 23 14:54:30 EDT 2020


On 2020-10-23 19:32, Pasha Stetsenko wrote:
> Thanks for all the replies!
> Following Chris's advice, I tried to reduce the code to the smallest
> reproducible example (I guess I should have done it sooner),
> but here's what I came up with:
> ```
>    #include <cstring>
>    #include <Python.h>
> 
>    static int my_init(PyObject*, PyObject*, PyObject*) { return 0; }
>    static void my_dealloc(PyObject*) {}
> 
>    static void init_mytype(PyObject* module) {
>      PyTypeObject* type = new PyTypeObject();
>      std::memset(type, 0, sizeof(PyTypeObject));
>      Py_INCREF(type);
> 
>      type->tp_basicsize = static_cast<Py_ssize_t>(sizeof(PyObject));
>      type->tp_itemsize = 0;
>      type->tp_flags = Py_TPFLAGS_DEFAULT;
>      type->tp_new   = &PyType_GenericNew;
>      type->tp_name  = "mytype";
>      type->tp_doc   = "[temporary]";
>      type->tp_init  = my_init;
>      type->tp_dealloc = my_dealloc;
>      PyType_Ready(type);
>      PyModule_AddObject(module, "mytype", reinterpret_cast<PyObject*>(type));
>    }
> ```

You're setting the deallocation function to 'my_dealloc', but that 
function isn't deallocating the object.

Try something like this:

static void my_dealloc(PyObject* obj) {
     PyObject_DEL(obj);
}

[snip]


More information about the Python-list mailing list