How properly manage memory of this PyObject* array?? (C extension)
Fredrik Lundh
fredrik at pythonware.com
Sun Jul 9 04:52:21 EDT 2006
seberino at spawar.navy.mil wrote:
> Suppose a C extension locally built an array of PyObject* 's as
> follows...
>
> my_array = malloc(n * sizeof(PyObject*));
> for (i = 0; i < n; i++) {
> my_array[i] = PyList_New(0);
> }
>
> Q1: Must I do a Py_DECREF(my_array[i]) on all elements
> before exiting this C extension function?
if you're releasing my_array before existing, yes.
> (What if the elements got used in other objects?)
if other parts of your program storing pointers to the elements in your
array, those parts must make sure to increment the reference count when
copying the pointer.
that's the whole point of reference counting, of course: the count for
an object should, at all times, match the number of *active* references
your program has to that object.
> Q2: Must I do free(my_array); at end of function??
unless some other part of your program holds on to it, of course you
have to release it. it's a bit surprising that you have to ask this,
really -- any C tutorial should explain how malloc/free works.
> What if my_array[i]'s are used in other objects so that I can't
> necessarily just nuke it!!!
if those other objects do proper reference counting, everything will
work find. if they don't, your program will crash sooner or later, no
matter what you do in the function that allocates my_array.
</F>
More information about the Python-list
mailing list