title: Garbage collection segfault in python code while `gc.garbage` is empty
body: <p>The following code works fine and prints out an <strong>empty list</strong> (on <code>python3.4</code>):</p>
  
  <pre><code>import gc
  # code interfacing with C and cython
  print(gc.garbage, flush=True)
  </code></pre>
  
  <p>Appending this line to the very end makes it segfault:</p>
  
  <pre><code>gc.collect()
  </code></pre>
  
  <p>It seems like it is pure luck that the automatic collection does not happen on its own (it took me some time to get reproducible error). The collection is not ran at "end of program" either because I am running this interactively.</p>
  
  <p>Some googling led me to believe that some of the C/Cython code is creating/destroying objects without telling python that those objects are already removed from memory. Then python tries to remove them and crashes.</p>
  
  <p>How can I find what those objects are? I thought that they would be in <code>gc.garbage</code> before the crash inducing <code>gc.collect()</code>?</p>
  
  <p>Or are my assumptions completely incorrect?</p>
  
  <p>Prepending an <code>gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_LEAK)</code> to this code leads to a python exception instead of a segfault.</p>
  
  <pre><code>---&gt; print(gc.garbage, flush=True)
       gc.collect()
  ...
  ReferenceError: weakly-referenced object no longer exists
  </code></pre>
  
  <p>Edit: changed/simplified after comments from one of the answers</p>