DECREFing and PyArray functions in C Extensions

Travis Oliphant olipt at mayo.edu
Fri May 26 09:49:14 EDT 2000


I've been asked to post a follow-up to my recent post on decrementing 
reference counts in C extensions to Python.  

> The short answer is, everything must be DECREF'd.   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.
> 

This is still my advice, but I would reword it: 

Every PyArrayObject that you successfully receive from a PyArray_XXXXXX
call has an increased reference count (you own a reference).  Unless you
are returning the object to the user (using return PyArray_Return(obj) or
PyArray_BuildValue with the "N" construct) you must DECREF the object
before leaving the subroutine or you will create a memory leak..

> 
> In the same message you later point out that a call to
> PyArray_ContiguousFromObject must include a PyDECREF before returning from
> the C routine.  However, on page 69 of the numericalpython.pdf manual the
> array "array" is not called in a PyDECREF call before a return NULL;  It is
> called before a successful return of the routine at the end of the code.
> The calling of PyDECREF is not clear.  We could all use some help on this
> since memory leaks are evil.  Can you post a clarifier to when PyDECREF
> must be used?  Thanks for any help.
>

I'm not sure which example you are talking about.  In my version of the
PDF documentation there are two examples which use "array" as a
variable name: one on page 71 and another on page 72.    The context seems
to indicate you are talking about the example showing how to accept input
data from any sequence type (my page 72).

If this is the case, then the reason Py_DECREF(array) is not called for
the NULL return is that if the PyArray_ContiguousFromObject call returned
NULL then there is no object whose reference count needs to decremented.
Note that it would not be a problem to use Py_XDECREF(array) here if it
made things more clear since Py_XDECREF(obj) does nothing if obj is NULL.

Py_XDECREF(obj) is used whenever you are unsure of whether or not obj is
NULL.  I use this call often in the fail: part of my subroutines.

Let me know if I can clarify things further. 

-Travis


 




More information about the Python-list mailing list