title: How do I debug refcounts in a Python C-extension the easiest way?
body: <p>So I have put together a few Python C-extensions and although their respective behaviors are verified, I'd like to verify this by some refcount debugging.</p>
  
  <p>How can I verify that I have inserted the INC/DEC refcounts properly? I want to do this verification from a black box perspective, that is, how should a function's input/output/memory look if all refcounts have been done properly?</p>
  
  <p>My first approach would be to use sys.getrefcount(obj) and check all the input/output objects' refcounts to see they are ok. Secondly, I could also perhaps check the memory used to see that there is no memory leak.</p>
  
  <p>But I have never really done this before, so what's the easiest and most correct way to do this?</p>
  
  <p><strong>Please note:</strong>
  I don't want to use any Cython style libraries, I'd rather do the C nitty gritty myself to learn the fundamentals.</p>
  
  <p><strong>Solution:</strong> So as suggested I built a debug enabled Python interpreter. I thought it would be tricky, but it wasn't. As per this <a href="http://code.activestate.com/recipes/67112-help-in-debugging-memory-problems/" rel="nofollow">recipe</a> I added those exact lines to <code>Objects/object.c</code>. After that all I had to do in the downloaded Python source directory was:</p>
  
  <pre><code>./configure --with-pydebug --prefix=/usr/local/python/
  make
  make install
  </code></pre>
  
  <p>With regards to building the C-extension to this new interpreter, all that had to be done on that front was to point the <code>include_dirs</code> tag in the Extension in <code>setup.py</code> to <code>'/usr/local/python/include/python2.7'</code>, and then running the build and install command with the new interpreter. Once that was done I could add just add <code>_Py_CountReferences(stderr);</code> lines in the c code and the refcount would be dumped to stderr (console). Very good to see what changes the refcount, and how it increments/decrements as the code progresses. </p>