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

Mike Rovner mike at nospam.com
Wed Oct 8 15:10:12 EDT 2003


Christian Seberino wrote:
>    return Py_BuildValue("s", my_string);
>
>
> If my_string allocated dynamically:
> ==========================
> Will Python successfully handle garbage collection of my_string?

Nope. It's your string, you handle it.

> Will there be any problems because it was built within my C function?

No problems.

> (I would think Python will successfully receive a COPY of my_string
> but that the original my_string object will be a memory leak!!!)

Agreed.

So don't do that. Instead write (untested):

PyObject* ret = Py_BuildValue("s", my_string);
free(my_string);
return ret;

> If my_string allocated statically:
> ==========================
> Don't all statically declared objects get killed when you exit a C
> function? This is not a problem because Python will get a COPY right?

Rigth.
AFAIUC, static objects "get killed" along with your whole program.
Probably you are talking about function local objects (dynamically)
allocated in stack.

> (This seems "safer" until my dynamic question above gets answered but
> with static guys you lose flexibility with the SIZE of the string of
> course.)

"All what you're doing is safe as long as you understand what are you doing"
(c) not me

HTH,
Mike








More information about the Python-list mailing list