title: How to free memory allocated by external C libraries interfacing with Cython module where the memory is ultimately returned to a Python process?
body: <p>I am brand new to Cython, but basically I have this application that needs significant performance increases, and so my team and I are trying to rewrite our bottlenecks in Cython and in C.</p>
  
  <p>For the slowest part of our application, I wrote some C code that gets compiled into a library and <code>cdef extern</code> imported into a Cython module, which I believe is a <code>.pyx</code> file. Essentially, the code in the <code>pyx</code> file is basically just a wrapper that returns calls to the C library functions. Finally, there is a Python process (the main application) that imports all of the functions defined in the <code>pyx</code> file and uses these results.</p>
  
  <p>I believe I have a memory leak because in the C code, the results that I need to pass to the Python process are at times dynamically allocated. My issue is that I don't know how to free this memory once the Python process has made use of it.</p>
  
  <p><strong>Example Python Code</strong></p>
  
  <pre class="lang-py prettyprint-override"><code>from examplecython import *
  
  def foo(data):
      context = data.context
      value = call_pyx_function(context, data)
      return value
  
  def bar(results):
      for data in results:
          res = foo(data)
          do_something_with_res(res)
          # I want to free here
  </code></pre>
  
  <p><strong>Example Cython Code</strong></p>
  
  <pre><code>cdef extern from "my_lib.h"
      char * my_function(const char * context, int data)
  
  def call_pyx_function(context: bytes, int x):
      return my_function(context, x)
  </code></pre>
  
  <p><strong>Example C Code</strong></p>
  
  <pre class="lang-c prettyprint-override"><code>
  #define BUFSIZE 256
  
  char *
  my_function(const char * context, int x) {
      char * retbuf;
      int res;
  
      retbuf = (char *)malloc(BUFSIZE * sizeof(char));
  
      res = do_some_math(x, context);
  
      int length = snprintf(retbuf, BUFSIZE, "%d", res);
      if (length &gt;= BUFSIZE) {
          exit(EXIT_FAILURE);
      }
  
      return retbuf;
  }
  </code></pre>
  
  <p>If anyone has any suggestions for how and where I can free this memory, that would be very much appreciated.</p>