[capi-sig] Naive question on references

Gustavo Carneiro gjcarneiro at gmail.com
Thu Aug 13 00:46:15 CEST 2009


2009/8/12 Jérôme Fuselier <jerome.fuselier at free.fr>

> Hello,
>  I have a working application which extends a C api to python and
> everything works as I wanted to. I'm now in a cleaning phase where I want to
> improve my stuff, especially to avoid memory leak.
>
> Here is a simple example of what seems correct to me but for which I would
> like an expert opinion :
>
> PyObject * test() {
>   PyObject *dict = PyDict_New();
>   // ... some code to initialize dict
>
>   PyObject *item = PyDict_GetItemString(dict, "key");
>   Py_INCREF(item);
>   Py_DECREF(dict);
>   return item;
> }
>
> As far as I understood, PyDict_GetItemString() returns a borrowed reference
> to the element so I need to do Py_INCREF(item) to own this reference. But is
> this needed ? If I only do return item, will the received item be owned by
> the caller of the test method ?


Yes, you do need the INCREF.  If you remove the Py_INCREF(item) line, then
when Py_DECREF(dict) is executed the dictionary could be freed, along with
the object pointed to by 'item'.

The code above is correct, and the caller of your test() function is
responsible for DECREF'ing the returned value.

-- 
Gustavo J. A. M. Carneiro
INESC Porto, Telecommunications and Multimedia Unit
"The universe is always one step beyond logic." -- Frank Herbert


More information about the capi-sig mailing list