title: When to Py_INCREF?
body: <p>I'm working on a C extension and am at the point where I want to track down memory leaks.  From reading Python's documentation it's hard to understand when to increment / decrement reference count of Python objects.  Also, after couple days spending trying to embed Python interpreter (in order to compile the extension as a standalone program), I had to give up this endeavor.  So, tools like Valgrind are helpless here.</p>
  
  <p>So far, by trial and error I learned that, for example, <code>Py_DECREF(Py_None)</code> is a bad thing... but is this true of any constant?  I don't know.</p>
  
  <p>My major confusions so far can be listed like this:</p>
  
  <ol>
  <li>Do I have to decrement refcount on anything created by <code>PyWhatever_New()</code> if it doesn't outlive the procedure that created it?</li>
  <li>Does every <code>Py_INCREF</code> need to be matched by <code>Py_DECREF</code>, or should there be one more of one / the other?</li>
  <li>If a call to Python procedure resulted in a <code>PyObject*</code>, do I need to increment it to ensure that I can still use it (forever), or decrement it to ensure that eventually it will be garbage-collected, or neither?</li>
  <li>Are Python objects created through C API on the stack allocated on stack or on heap?  (It is possible that <code>Py_INCREF</code> reallocates them on heap for example).</li>
  <li>Do I need to do anything special to Python objects created in C code before passing them to Python code?  What if Python code outlives C code that created Python objects?</li>
  <li>Finally, I understand that Python has both reference counting and garbage collector: if that's the case, how critical is it if I mess up the reference count (i.e. not decrement enough), will GC eventually figure out what to do with those objects?</li>
  </ol>