C extension question about avoiding memory leaks with the object returned...

Christian Seberino seberino at spawar.navy.mil
Wed Oct 8 20:29:03 EDT 2003


Martin

Thanks.  Is there no way to return a dynamically allocated C string in your
C extension without making a memory leak?  Must all strings be allocated to be
a fixed size at compile time like this...???

#define MAX_LENGTH 20
...
char my_string[MAX_LENGTH];
...
return Py_BuildValue("s", my_string);

(This is what I meant by "statically allocated string".)

Will *this* make a memory leak as well?

Chris

martin at v.loewis.de (Martin v. Löwis) wrote in message news:<m3r81npnfe.fsf at mira.informatik.hu-berlin.de>...
> seberino at spawar.navy.mil (Christian Seberino) writes:
> 
> >    return Py_BuildValue("s", my_string);
> 
> In this case, Py_BuildValue is very expensive. Use PyString_FromString
> instead.
> 
> > If my_string allocated dynamically:
> > ==========================
> > Will Python successfully handle garbage collection of my_string?
> 
> No. The resulting Python string object will be a copy; the original
> string is considered read-only, and no attempt to release it is made.
> 
> > Will there be any problems because it was built within my C function?
> 
> If you don't release it, there will be a memory leak. Apart from that:
> no.
> 
> > If my_string allocated statically:
> > ==========================
> > Don't all statically declared objects get killed when you exit a C function?
> 
> You might need to explain what a statically declared string is, in
> C. If you are talking about string literals: no, they don't get killed
> when a C function exits. They exist from the start of the program
> until it ends.
> 
> > This is not a problem because Python will get a COPY right?
> 
> Right.
> 
> Regards,
> Martin




More information about the Python-list mailing list