c - *** Error in `python': munmap_chunk(): invalid pointer: 0x00007fdfb8c28950 *** -
i want write c-extension python, can see below ,the aim of code calculate euclidean-dist 2 lists of float.
the c code:
#include <python2.7/python.h> #include <math.h> static pyobject* cutil_euclidean_dist(pyobject* self, pyobject* args) { pyobject *seq_a, *seq_b; int n; float * array_a,* array_b; pyobject *item; printf("prepare check input"); pyarg_parsetuple(args,"ioo", &n , &seq_a, &seq_b); if (!pysequence_check(seq_a) || !pysequence_check(seq_b)) { pyerr_setstring(pyexc_typeerror, "expected sequence"); return null; } array_a =(float *)malloc(sizeof(float)*n); array_b =(float *)malloc(sizeof(float)*n); if (null == array_a || null == array_b){ pyerr_setstring(pyexc_typeerror, "malloc failed!"); return null; } printf("%d",array_a==null); printf("%d",array_b==null); printf("malloc yes "); printf("n=%d",n); int i; for(i=0;i<n;i++){ printf("111"); item = pysequence_getitem(seq_a,i); printf("after item"); if (!pyfloat_check(item)) { printf("in float check"); free(array_a); /* free memory before leaving */ free(array_b); free(seq_a); free(seq_b); pyerr_setstring(pyexc_typeerror, "expected sequence of float"); return null; } array_a[i] = pyfloat_asdouble(item); printf("a=%f",array_a[i]); py_decref(item); item = pysequence_getitem(seq_b,i); if(!pyfloat_check(item)) { free(array_a); free(array_b); free(seq_a); free(seq_b); pyerr_setstring(pyexc_typeerror, "expected sequence of float"); } array_b[i] = pyfloat_asdouble(item); py_decref(item); } printf("array analyze yes"); double sum = 0; for(i=0;i<n;i++){ double delta = array_a[i] - array_b[i]; sum += delta * delta; } free(array_a); free(array_b); free(seq_a); free(seq_b); return py_buildvalue("d",sqrt(sum)); } static pymethoddef cutil_methods[] = { {"c_euclidean_dist", (pycfunction)cutil_euclidean_dist,meth_varargs,null}, {null,null,0,null} }; pymodinit_func initcutil(void) { py_initmodule3("cutil", cutil_methods, "liurui's c extension python"); }
the python code:
import cutil cutil.c_euclidean_dist(2,[1.0,1.0],[2.0,2.0])
the result:
*** error in `python': munmap_chunk(): invalid pointer: 0x00007fdfb8c28950 *** (core dumped)
so can not succeed in calling function.
who can me problem? lot
i not know what's wrong it.
by way: when complie code, gcc asked me add -fpic , when add -fpic,the says gcc can not find python.h changed:
#include <python.h>
into this:
#include <python2.7/python.h>
then ok
when comment 2 sentences, code runs well:
free(seq_a); free(seq_b);
but think without 2 sentences , there memory leak because seq_a , seq_b not freed
you can use free()
deallocate memory allocated using malloc()
.
seq_a
, seq_b
incorrectly trying free not allocated via malloc
.
also, should check out pyobject
, reference counting chapter in python docs.
Comments
Post a Comment