title: Segfault at Py_Finalize (python 2.5) in single threaded C program
body: <p>In this following hello world C program, I am both extending and embedding Python.</p>
  
  <p><strong>spam.c</strong>:</p>
  
  <pre><code>#include &lt;Python.h&gt;
  
  static PyObject *
  spam_echo(PyObject *self, PyObject *args) {
      const char *command;
      int sts;
  
      if (!PyArg_ParseTuple(args, "s", &amp;command))
          return NULL;
      sts = printf("%s\n", command);
      return Py_BuildValue("i", sts);
  }
  
  static PyMethodDef SpamMethods[] = {
      {"echo", spam_echo, METH_VARARGS, "Prints passed argument"},
      {NULL, NULL, 0, NULL}
  };
  
  PyMODINIT_FUNC
  initspam(void) {
      (void) Py_InitModule("spam", SpamMethods);
  }
  
  int main(int argc, char *argv[]) {
      PyObject *args;
      PyObject *arg;
      PyObject *result;
      PyObject *moduleName;
      PyObject *module;
      PyObject *func;
  
      Py_SetProgramName(argv[0]);
      Py_Initialize();
      initspam();
  
      PyRun_SimpleFile(fopen("foo.py", "r"), "foo.py");
  
      moduleName = PyString_FromString("__main__");
      module = PyImport_Import(moduleName);
      Py_DECREF(moduleName);
      if (!module) {
          return 1;
      }
  
      func = PyObject_GetAttrString(module, "foo");
      Py_DECREF(module);
      if (!func || !PyCallable_Check(func)) {
          return 1;
      }
  
      args = PyTuple_New(1);
      arg = Py_BuildValue("s", "hello world");
      PyTuple_SetItem(args, 0, arg);
  
      result = PyObject_CallObject(func, args);
      Py_DECREF(arg);
      Py_DECREF(args);
      Py_DECREF(func);
  
      printf("== before\n");
      Py_Finalize();
      printf("== after\n");
  }
  </code></pre>
  
  <p>And here is the Python program invoked:</p>
  
  <p><strong>foo.py</strong>:</p>
  
  <pre><code>#!/usr/bin/python
  
  import spam
  
  def foo(cmd):
      spam.echo(cmd)
  </code></pre>
  
  <p>I compile with</p>
  
  <pre><code>gcc spam.c -I/usr/include/python2.5/ -lpython2.5
  </code></pre>
  
  <p>with GCC 4.2.4-1ubuntu4 and I am using python2.5-dev package on Ubuntu Hardy.</p>
  
  <p>Basically, I have a segfault at Py_Finalize as shows the output:</p>
  
  <pre><code>hello world
  == before
  Segmentation fault
  </code></pre>