title: Where should I put Py_INCREF and Py_DECREF on this block in Python C Extension?
body: <p>Whenever I called my function, memory usage is increased around +10M per call, so I think there is some memory leak here.</p>
  
  <pre><code>....
  PyObject *pair = PyTuple_New(2), *item = PyList_New(0);
  
  PyTuple_SetItem(pair, 0, PyInt_FromLong(v[j]));
  
  if(v[j] != DISTANCE_MAX &amp;&amp; (p[j] || d[0][j])){
    jp=j;
    while(jp!=istart) {
      PyList_Append(item, PyInt_FromLong(jp));
      jp=p[jp];
    }
  
    PyList_Append(item, PyInt_FromLong(jp));
  
    PyList_Reverse(item);
  }
  
  PyTuple_SetItem(pair, 1, item);
  
  return pair;
  ....
  </code></pre>
  
  <p>When I read <a href="http://docs.python.org/extending/extending.html#thin-ice" rel="noreferrer">document</a>, some calls like</p>
  
  <pre><code>void
  bug(PyObject *list)
  {
      PyObject *item = PyList_GetItem(list, 0);
  
      PyList_SetItem(list, 1, PyInt_FromLong(0L));
      PyObject_Print(item, stdout, 0); /* BUG! */
  }
  </code></pre>
  
  <p>need to put reference counts like this</p>
  
  <pre><code>void
  no_bug(PyObject *list)
  {
      PyObject *item = PyList_GetItem(list, 0);
  
      Py_INCREF(item);
      PyList_SetItem(list, 1, PyInt_FromLong(0L));
      PyObject_Print(item, stdout, 0);
      Py_DECREF(item);
  }
  </code></pre>
  
  <p>So, Where should I put Py_INCREF and Py_DECREF on my function?</p>