C API and memory allocation

Floris Bruynooghe floris.bruynooghe at gmail.com
Thu Dec 18 00:35:04 CET 2008

Hello again

On Dec 17, 11:06 pm, Floris Bruynooghe <floris.bruynoo... at gmail.com>
> So I'm assuming PyArg_ParseTuple()
> must allocate new memory for the returned string.  However there is
> nothing in the API that provides for freeing that allocated memory
> again.

I've dug a little deeper into this and found that PyArg_ParseTuple
(and friends) end up using PyString_AS_STRING() (Python/getargs.c:793)
which according to the documentation returns a pointer to the internal
buffer of the string and not a copy and that because of this you
should not attempt to free this buffer.

But how can python now know how long to keep that buffer object in
memory for?  When the reference count of the string object goes to
zero the object can be deallocated I though, and then your pointer
will point to something different all of a sudden.  Does this mean you
always have too keep a reference to the original objects when you've
extracted information from them with PyArg_Parse*() functions?  (At
least while you want to hang on to that information.)


More information about the Python-list mailing list