title: Numpy C-Api example gives a SegFault
body: <p>I'm trying to understand how the Python C- Api works, and I want to exchange numpy arrays between Python and a C Extension.</p>
  
  <p>So, I started this tutorial: <a href="http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html">http://dsnra.jpl.nasa.gov/software/Python/numpydoc/numpy-13.html</a></p>
  
  <p>Tried to do the first example there, a C module that calculates the trace of a 2d numpy array, was very neat for me, since I want to do elementary operations in 2d arrays also.</p>
  
  <pre><code>#include &lt;Python.h&gt;
  #include "Numeric/arrayobject.h"
  #include&lt;stdio.h&gt;
  
  int main(){
  Py_Initialize();
  import_array();
  }
  
  static char doc[] =
  "This is the C extension for xor_masking routine";
  
      static PyObject *
      trace(PyObject *self, PyObject *args)
      {
      PyObject *input;
      PyArrayObject *array;
      double sum;
      int i, n;
  
      if (!PyArg_ParseTuple(args, "O", &amp;input))
      return NULL;
      array = (PyArrayObject *)
      PyArray_ContiguousFromObject(input, PyArray_DOUBLE, 2, 2);
      if (array == NULL)
      return NULL;
  
      n = array-&gt;dimensions[0];
      if (n &gt; array-&gt;dimensions[1])
      n = array-&gt;dimensions[1];
      sum = 0.;
      for (i = 0; i &lt; n; i++)
      sum += *(double *)(array-&gt;data + i*array-&gt;strides[0] + i*array-&gt;strides[1]);
      Py_DECREF(array);
      return PyFloat_FromDouble(sum);
      }
  
  static PyMethodDef TraceMethods[] = {
      {"trace", trace, METH_VARARGS, doc},
      {NULL, NULL, 0, NULL}
  };
  
  PyMODINIT_FUNC
  inittrace(void)
  {
      (void) Py_InitModule("trace", TraceMethods);
  }
  
  
  }
  </code></pre>
  
  <p>The module's name is trace, and it is compiled with the setup.py file:</p>
  
  <pre><code>from distutils.core import setup, Extension
  
  module = Extension('trace', sources = ['xor_masking.cpp'])
  setup(name = 'Trace Test', version = '1.0', ext_modules = [module])
  </code></pre>
  
  <p>The file is compiled, trace.so is imported in IPython, but when I try to use the method trace(), I get a Segmentation Fault, I don't know why.</p>
  
  <p>I run this with  Fedora 15, Python 2.7.1, gcc 4.3.0, Numpy 1.5.1</p>