Py_DECREF Question:

Scott David Daniels Scott.Daniels at Acm.Org
Mon Aug 15 20:57:01 CEST 2005

Jeremy Moles wrote:
> When I add an object created locally to a mapping or sequence ...
> I need to call Py_DECREF on the object, right? ... for example:
>     PyObject* list = Py_Buildvalue("[]");
>     ...
> 	PyObject* num  = Py_BuildValue("i", 10);
> 	PyList_Append(list, num);
>     ...
> ... does anyone have any tools and/or recommendations for detecting 
> memory leaks when writing extension modules in C? ...

Here's how to answer this for yourself:
      PyObject* list = Py_Buildvalue("[]");
      int precount;
          PyObject* num  = Py_BuildValue("i", 10);
          precount = num.ob_refcnt;
          PyList_Append(list, num);
          <here compare precount and num.ob_refcnt>

If you need to do the DECREF, precount should exceed num.ob_refcnt.
If they match, the "PyList_Append" call "stole" your reference.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list