Question

I'm building a nested set of tuples in a C++ Python extension. However, I'm having some problems with managing reference counts.

The minimal code to re-create this memory leak:

PyObject *outer = PyTuple_New(outer_size);
for (size_t index = 0; index < outer_size; ++index) {
    PyObject *inner = Py_BuildValue("iiiiiiiiid", ...);
    PyTuple_SetItem(outer, index, inner);
}
Py_CLEAR(outer);
Py_INCREF(Py_None);
return Py_None;

Now, if I instead replace the PyTuple_SetItem(outer, index, inner) with a Py_CLEAR(inner), the memory usage doesn't grow over time.

Am I wrong about the outer tuple stealing the reference to the inner tuple? Is there some other reason memory wouldn't be reclaimed?

Was it helpful?

Solution

Turns out I was mistaking a very slowly growing memory usage (for other reasons) for a memory leak. Had the reference counting been failing, it would have grown substantially faster. So, it's true. This code doesn't leak.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top