Refrence Counting

Erik Johnson efj at mintec.com
Tue Jun 19 14:00:51 EDT 2001


I am unclear about my responsibilities in refrence counting.  I am
trying to use Python as an extension language.  In the code snip below
I wish to return an "associative array"/"dictionary" of information. 
Upon looking through the newsgroup I got a bit paranoid about memory
leaks due to incorrect reference counting.  Do I need to decrement the
reference count for the second dictionary below (grades)?  When I use
PyStringFromString() it creates the object with a reference count of
one, then it is added to my dictionary with PyDict_SetItem() does this
increment it again?  Should I create it in a seperate step then use
PyDict_SetItem() and then decrement it?

Thanks in advance for any help.
   Erik Johnson

int _PY_GetCutData(PyObject *self, PyObject *args)
{
   int            i,
                  numg;
   PyObject      *ret = NULL,
                 *grades = NULL;   

   do
   {
      ret = PyDict_New();
      if(!ret)
         break;

      if(!PyDict_SetItem(ret, PyString_FromString("Area"), 
         PyString_FromString(cr->area)))
         break;

      if(!PyDict_SetItem(ret, PyString_FromString("TotalTons"), 
         PyFloat_FromDouble(_GetTotalCutTons(cr))))
         break;          
      
      grades = PyDict_New();
      if(!grades)
         break;

      if(!PyDict_SetItem(ret, PyString_FromString("AvgGrade"),
grades))
         break;    
      
      for(i = 0 ; i < numg ; ++i)
      {
         if(!PyDict_SetItem(ret, PyInt_FromLong(i), 
            PyFloat_FromDouble(_GetAvgCutGrade(cr, i))))
            break;    
      }
      if(i != numg)
         break;
      
      return ret;               
   }while(FALSE);
   Py_XDECREF(ret);
   Py_XDECREF(grades);
   return 0;
}



More information about the Python-list mailing list