How to identify memory leaks in extensions?

Les Schaffer godzilla at
Fri May 12 17:17:10 CEST 2000

Travis 'numpy-mmeory' oliphant said:

> The short answer is, everything must be DECREF'd.  

okay. i am confused now. even if one is __returning__ the array?

    indep = (PyArrayObject *) PyArray_FromDims( IND_DIM, &dims[1], PyArray_DOUBLE);
    dep  =  (PyArrayObject *) PyArray_FromDims( DEP_DIM, dims,     PyArray_DOUBLE);

    indepPtr = (double *)indep->data;

    /* now let PyArray_As2D re-arrange, if necessary (?),  */
    /* our array and set the pointers to the rows of array */
    PyArray_As2D( (PyObject**)&dep, (char ***) &numarr, 
		  &dims[0], &dims[1], PyArray_DOUBLE ); 

    /* do stuff */

    return Py_BuildValue("(OO)", indep, dep);

okay, from your post those 'OO' should be 'NN'. but even then ...

> Whenever you use a PyArray_XXXXXXX construct that gives you back a
> PyArrayObject, you own a reference.  You must DECREF before leaving
> the subroutine or you have a memory leak.

you're saying i have to DECREF indep and dep before i return????? its
confusing. i allocate arrays with PyArrayXXX to do stuff with and
return them, in my python code i set references to them. somehow the
'setting reference in the python code' is an INCREF over and above the

hmmmm.... i'm glad someone told me about that ;-) i guess i had just
asumed taht the INCREF happens in the python call when i go

arr1, arr2 = my_func()     # my_func returning those indep, dep arrays

but not before. oh well.

so, lets see. every PyArray does one INCREF. every Py_BuildValue does
another one if you use the 'O', and when you set a refernece equal to
it in a return value, thats yet another?????? or maybe i am confusing
the last INCREF with the first one.

so when i go in python:

x = 3

the 3 is created in storage and there is one reference to it, then
when i set x = to it, thats another INCREF.

makes no sense. cause when i go x = 4, that 3 should go away
sometime. which would make on think the INCREF is done at time of
object creation. 

but if i go 

x = 3
y = x

that y = adds a reference to the 3 object.


les schaffer

More information about the Python-list mailing list