[Matrix-SIG] Freeing malloc'd array in Python

Konrad Hinsen hinsen@cnrs-orleans.fr
Mon, 7 Sep 1998 11:04:07 +0200

> I used the following to allocate a PyArrayObect of known size and then
> copied the data into the data portion of the PyArrayObject.  Finally, I
> lose the memory leak by freeing the now useless array that came from my
> 'C' function.  This works (including proper memory management of the
> array in Python),  but seems kind of inelegant since I have to copy a
> perfectly good block of memory into a different location.

There is no other solution, as far as I know, at least no easy one.
PyArray_FromDimsAndData() is meant for wrapping static arrays,
i.e. arrays that cannot be freed.

If you want to avoid copying, and don't mind some added complexity,
you could try the following: in addition to the array object (created
with PyArray_FromDimsAndData()), return a Python CObject from your C
module which wraps the pointer to the C array and a pointer to a
function called upon deletion which frees the array. Then make sure
that both Python objects are deleted at the same time.

Yet another way, if you don't care messing around with undocumented
data structures, is creating a small Python array with its
data space, freeing the data space, substituting a pointer to the
data space you have, and patch the other entries in the array data
structure to reflect the correct size.

But unless you are working with really large arrays, just stick
to the solution you have!

I don't know if there are many C libraries out there that return
allocated memory blocks to the caller (which I think is not a good
approach for a variety of reasons). If there are, then NumPy should
offer some way to handle freeing.
Konrad Hinsen                            | E-Mail: hinsen@cnrs-orleans.fr
Centre de Biophysique Moleculaire (CNRS) | Tel.: +33-
Rue Charles Sadron                       | Fax:  +33-
45071 Orleans Cedex 2                    | Deutsch/Esperanto/English/
France                                   | Nederlands/Francais