title: Cython: segfault when using PyMem_Malloc in a class
body: <p>I am having a hard time with what to me seems almost a textbook <code>PyMem_*</code> implementation from the <a href="http://cython.readthedocs.io/en/latest/src/tutorial/memory_allocation.html" rel="nofollow noreferrer">Cython manual</a> (I'm in an IPython shell):</p>
  
  <pre><code>In [2]: %%cython -f
     ...: from cpython.mem cimport PyMem_Malloc, PyMem_Realloc, PyMem_Free
     ...: from libc.string cimport memcpy
     ...: cdef class A:
     ...:     cdef unsigned char **data
     ...:     def __cinit__(self):
     ...:         print('Allocating memory.')
     ...:         self.data = &lt;unsigned char **&gt;PyMem_Malloc(6)
     ...:         if not self.data:
     ...:             raise MemoryError()
     ...:
     ...:     cpdef void assign(self):
     ...:         cdef unsigned char a1[3]
     ...:         cdef unsigned char a2[3]
     ...:         a1 = bytearray(b'123')
     ...:         a2 = bytearray(b'abc')
     ...:         print('Assigning a1.')
     ...:         memcpy(self.data[0], a1, 3)
     ...:         print('Assigning a2.')
     ...:         memcpy(self.data[1], a2, 3)
     ...:         print(self.data[1][: 3])
     ...:
     ...:     def __dealloc__(self):
     ...:         print('Releasing memory.')
     ...:         PyMem_Free(self.data)
     ...: a = A()
     ...: a.assign()
     ...: del(a)
     ...: b = A()
     ...: b.assign()
     ...: del(b)
  Allocating memory.
  Assigning a1.
  Assigning a2.
  Segmentation fault (core dumped)
  </code></pre>
  
  <p>What is wrong with my code? The only difference I see from the manual example is that I am using a 2D array of characters (they are not NUL terminated strings), so maybe I am doing something wrong there?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>The segfault happens at random points. I doubled the instantiation and deletion lines because most times this happens on the second pass. Or even if I run the same Cython cell twice in a row. </p>
  
  <p>Thanks.</p>