codehaus


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Debugging a memory leak


Thanks MRAB, this was it.
I guess I was thinking about tp_dealloc as a C++ destructor, where the base
class' destructor is called automatically.

On Fri, Oct 23, 2020 at 11:59 AM MRAB <python at mrabarnett.plus.com> wrote:

> 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]
> --
> https://mail.python.org/mailman/listinfo/python-list
>