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

seberino at spawar.navy.mil seberino at spawar.navy.mil
Mon Jul 17 23:52:41 EDT 2006


> 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).

OK, I'll read your 'required reading' I promise.  Let me just make the
obvious
obvious for a minute.  Your 'requirements' above only mention
Py_INCREFs and Py_DECREFs and never mention free(my_array).
Hence, I will assume the answer to my previous question is that I do
NOT
have to do free(my_array) because Py_INCREFs and Py_DECREFs will
allow garbage collection to take care of even the malloc'd part that
hold the pointers to the objects.

By the way, we are allowing garbage collector to free different
elements (pointers)
of my_array one at a time here.  I just found out that curiously
enough, you CANNOT
do this in C with primitive types.

i.e. my_int_array = malloc(5 * sizeof(int));

You CANNOT do this...
       free(&my_int_array[1]);
       free(&my_int_array[2]);
       free(&my_int_array[3]);
       ...etc.
You can ONLY free the entire enchilada all at the same time...
         free(my_int_array);

Chris




More information about the Python-list mailing list