title: Debugging reference counting memory leaks in Python C extension modules
body: <p>I'm trying to determine if there are any reference counting memory leaks in a Python C extension module. Consider this very simple test extension that leaks a <code>date</code> object:</p>
  
  <pre><code>#include &lt;Python.h&gt;
  #include &lt;datetime.h&gt;
  
  static PyObject* memleak(PyObject *self, PyObject *args) {
      PyDate_FromDate(2000, 1, 1); /* deliberately create a memory leak */
      Py_RETURN_NONE;
  }
  
  static PyMethodDef memleak_methods[] = {
      {"memleak",  memleak, METH_NOARGS, "Leak some memory"},
      {NULL, NULL, 0, NULL}        /* Sentinel */
  };
  
  PyMODINIT_FUNC initmemleak(void) {
      PyDateTime_IMPORT;
      Py_InitModule("memleak", memleak_methods);
  }
  </code></pre>
  
  <p>PyDate_FromDate creates a new reference (i.e. internally calls Py_INCREF) and since I never call Py_DECREF, this object will never get garbage collected.</p>
  
  <p>However, when I call this function, the number of objects being tracked by the garbage collector doesn't seem to change before and after the function call:</p>
  
  <pre><code>Python 2.7.3 (default, Apr 10 2013, 05:13:16)
  [GCC 4.7.2] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  &gt;&gt;&gt; from memleak import memleak
  &gt;&gt;&gt; import gc
  &gt;&gt;&gt; gc.disable()
  &gt;&gt;&gt; gc.collect()
  0
  &gt;&gt;&gt; len(gc.get_objects()) # get object count before
  3581
  &gt;&gt;&gt; memleak()
  &gt;&gt;&gt; gc.collect()
  0
  &gt;&gt;&gt; len(gc.get_objects()) # get object count after
  3581
  </code></pre>
  
  <p>And I can't seem to find the leaked <code>date</code> object at all in the list of objects returned by <code>gc.get_objects()</code>:</p>
  
  <pre><code>&gt;&gt;&gt; from datetime import date
  &gt;&gt;&gt; print [obj for obj in gc.get_objects() if isinstance(obj, date)]
  []
  </code></pre>
  
  <p>Am I missing something here about how <code>gc.get_objects()</code> works? Is there another way to demonstrate that the memleak() function has a memory leak?</p>