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

Martin v. Löwis martin at v.loewis.de
Thu Oct 9 00:25:25 EDT 2003


seberino at spawar.navy.mil (Christian Seberino) writes:

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

No. You will need to release the dynamically allocated string, after
calling PyString_FromString. How precisely to do that depends on how
precisely it was allocated, but assuming it was allocated with
malloc(3), you should release it with free(3).

> #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?

No.

Regards,
Martin




More information about the Python-list mailing list