I'm writing a Python C API and in my c-code I allocate a double array which I then wrap into a numpy array and send back to Python. The weird thing is that the memory is being freed in Python if I use PyMem_
functions to allocate the memory, but not if I use regular c-functions such as malloc/calloc
, giving me segmentation faults or errors such as 'pointer being freed was not allocated'.
Example of c-function called from Python:
static PyObject* c_function_called_from_python(...){
int nrElem;
npy_intp dims[1];
PyObject *array;
double *data;
dims[0] = nrElem;
data = PyMem_Calloc(nrElem, sizeof(double)); // Does not work
// data = calloc(nrElem, sizeof(double)); // Do work
array = PyArray_SimpleNewFromData(1, dims, NPY_DOUBLE, (void *) data);
PyArray_ENABLEFLAGS((PyArrayObject *) array, NPY_ARRAY_OWNDATA);
return array;
}
Is there something special about PyMem_
functions that cause the memory to be freed?