How properly manage memory of this PyObject* array?? (C extension)

Fredrik Lundh fredrik at pythonware.com
Fri Jul 14 02:56:17 EDT 2006


seberino at spawar.navy.mil wrote:

> Now it would appear that if you **malloc an array of PyObjects**
> (call it FOO[]) then you have an ambiguity....
> 
> The PyObject elements will be freed *for us* eventually by garbage
> collector.
 >
> Hence, we can't ever do 'free(FOO); ' because we don't know when
> garbage collector will free FOO[0], FOO[1], FOO[2], etc.

you're not quite getting how reference counting works.  the fact that 
you have a pointer to a Python object stuffed away somewhere is 
completely irrelevant to the Python garbage collector; all it cares 
about is the reference count of the object itself.  if the reference 
count is not zero, someone somewhere might have a pointer to the object,
so the object must be preserved.  if the reference count drops to zero, 
nobody is supposed to have a pointer anymore, so the object can be removed.

if you use malloc to allocate a memory block and store PyObject pointers 
in it, you must

1) make sure that the reference count is *incremented* (Py_INCREF) when 
you add the objects (unless the object is new; when you create an 
object, the reference count is set to 1).  this tells Python that you 
have a pointer to an object that you plan to use some time in the future.

2) make sure that the reference count is *decremented* (Py_DECREF) if 
you remove the objects  (this tells Python that *you* won't access the 
object any more; if nobody else uses it either, it can safely be removed).

required reading:

     http://docs.python.org/api/objects.html

</F>




More information about the Python-list mailing list