I would like to free memory allocated a variable that is a pointer-to-pointer (or a "double pointer" -- not to be confused with pointer to a double datatype.)
Suppose the pointer-to-pointer is **ptr
and (for simplicity) it is a 10x10 array of integers. Following the documentation, I see that one way of allocating space is as follows.
from cpython.mem cimport PyMem_Malloc, PyMem_Free
## Allocate memory
cdef int **ptr = <int **>PyMem_Malloc(sizeof(int *) * 10)
cdef i;
for i in range(10):
ptr[i] = <int *>PyMem_Malloc(sizeof(int) * 10)
## Free memory
for i in range(10):
PyMem_Free(<void *>ptr[i])
PyMem_Free(<void *>ptr)
The documentation does not explicity mention what is the correct way to free a pointer-to-pointer. From my experience with programming in C, I guessed that this should be the recommended way. However, the free-memory syntax does not seem to work correctly, for when I compile (using distutils.core.setup), it seems to give me a familiar gcc-error -- indicating that I'm attempting to free unallocated memory.
python(4522,0x7fffd08143c0) malloc: *** error for object 0x1172c8054: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
This question is very much the Cython analogue of this question pertaining to C pointers.