SWIG typemap leading to a memory leak

Skip Montanaro skip at pobox.com
Mon Aug 18 22:44:18 CEST 2003


You need to DECREF the result of PyInt_FromLong(key):

    typemap(out) int {
       int key;
       PyObject *obj;
       $result = PyDict_New();  
       for(key=0; key < $1; key++) {
         obj = PyInt_FromLong(key);
         /* obj has a refcount of 1 */
         PyDict_SetItem($result, obj, obj);
         /* obj has a refcount of 3 */
         Py_DECREF(obj);
         /* obj has a refcount of 2 because of its use in the dictionary */
       }
    }

PyDict_SetItem will bump the reference counts of the objects you pass into
it.  When the dictionary goes away, it does its DECREFs, but all those
integers still have non-zero reference counts as a result of their initial
creation by PyInt_FromLong.  You have to take care of that.

Skip





More information about the Python-list mailing list