title: Wrapping C with Python; free(char *) invalid pointer
body: <p>I am following  <a href="http://intermediate-and-advanced-software-carpentry.readthedocs.org/en/latest/c++-wrapping.html" rel="nofollow noreferrer">this</a> tutorial on wrapping C/C++ with Python.  I have copied the example code verbatim, but will still list it below.</p>
  
  <h1>hello.c</h1>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;Python.h&gt;
  
  // Original C Function
  char * hello(char * what)
  {
      printf(&quot;Hello %s!\n&quot;, what);
      return what;
  }
  
  //  1) Wrapper Function that returns Python stuff
  static PyObject * hello_wrapper(PyObject * self, PyObject * args) 
  {
    char * input;
    char * result;
    PyObject * ret;
  
    // parse arguments
    if (!PyArg_ParseTuple(args, &quot;s&quot;, &amp;input)) {
      return NULL;
    }
  
    // run the actual function
    result = hello(input);
  
    // build the resulting string into a Python object.
    ret = PyString_FromString(result);
  
    free(result);
  
    return ret;
  }
  </code></pre>
  <p>The script <code>hello.c</code> defines a simple &quot;hello&quot; function, as well as a wrapper which returns a Python object, and (hypothetically) frees the c char * pointer.  <strong>This is where the code fails with the run-time error:</strong> <code>Error in '/usr/bin/python': free(): invalid pointer: 0x00000000011fbd44</code>.  While I believe the error should be limited to this scope, let's go over the rest of the wrapper just in case...</p>
  <p><code>hello.c</code> is included in the definition of a module, which allows its methods to be called in Python.  The module is defined as such:</p>
  <h1>hellomodule.c</h1>
  <pre><code>#include &quot;hello.c&quot;
  #include &lt;Python.h&gt;
  
  // 2) Python module
  static PyMethodDef HelloMethods[] =
  {
          { &quot;hello&quot;, hello_wrapper, METH_VARARGS, &quot;Say hello&quot; },
          { NULL, NULL, 0, NULL }
  };
  
  // 3) Module init function
  DL_EXPORT(void) inithello(void)
  {
      Py_InitModule(&quot;hello&quot;, HelloMethods);
  }
  </code></pre>
  <p>Finally, a Python script is implemented to build the module:</p>
  <h1>setup.py</h1>
  <pre><code>#!/usr/bin/python
  from distutils.core import setup, Extension
  
  # the c++ extension module
  extension_mod = Extension(&quot;hello&quot;, [&quot;hellomodule.c&quot;]) #, &quot;hello.c&quot;])
  
  setup(name = &quot;hello&quot;, ext_modules=[extension_mod])
  </code></pre>
  <p>Once <code>setup.py</code> is run, the module can be imported into any Python script, and its member functions <em>should</em> be accessible, and have proven to be, with the exception of the invalid pointer error.  I have spent many hours on this to no avail.  Please help.</p>