[Numpy-discussion] Some questions about PyArray_As2D.

Andrea Riciputi ariciputi at pito.com
Wed Dec 11 07:04:02 EST 2002

On Wednesday, Dec 11, 2002, at 14:33 Europe/Rome, Konrad Hinsen wrote:

>> 2) Next in the source code I've found the following memory allocation:
>> data = (char **)malloc(n*sizeof(char *));
>> without checking if malloc return NULL or not. As far as I know it's
>> not safe, even if it's very unlikely that this malloc would fail.
> Right. Did you submit a bug report?

Just done. By the way reading the code again and again I got another 
question. Here is the complete code fragment:

extern int PyArray_As2D(PyObject **op, char ***ptr, int *d1, int *d2, 
int typecode) {
     PyArrayObject *ap;
     int i, n;
     char **data;

     if ((ap = (PyArrayObject *)PyArray_ContiguousFromObject(*op, 
typecode, 2, 2)) == NULL)
         return -1;

     n = ap->dimensions[0];
     data = (char **)malloc(n*sizeof(char *));
     for(i=0; i<n; i++) {
         data[i] = ap->data + i*ap->strides[0];
     *op = (PyObject *)ap;  <=== It doesn't sound good to me!!!
     *ptr = data;
     *d1 = ap->dimensions[0];
     *d2 = ap->dimensions[1];
     return 0;

Looking at the marked line I started wondering about the fate of the 
object originally pointed by op. Without explicitly deallocating it you 
lost any chance to reach it. It turns out in a memory leakage. 
Obviously the same problem happend in PyArray_As1D function.

I'm very interested in this topic because I'm writing some Python 
extensions and I'd like to understand how I have to handle all these 
objects correctly. So how "long" does a Python object live? How can I 
release correctly the allocated memory?

Andrea Riciputi        <mailto:andrea.riciputi at libero.it>

"Science is like sex: sometimes something useful comes out,
   but that is not the reason we are doing it" -- (Richard Feynman)

More information about the NumPy-Discussion mailing list