From numpy matrix to C array. Segmentation fault (memory corruption) on 64bit architecture -
i'm trying build python c extension in order pass numpy matrix c array. following suggestions reported here:
http://wiki.scipy.org/cookbook/c_extensions/numpy_arrays
but when python tries run c line:
v=(float **)malloc((size_t) (n*sizeof(float)));
of follow portion of code:
float **_ptrvector(long n) { float **v; v=(float **)malloc((size_t) (n*sizeof(float))); if (!v) { printf("in **ptrvector. allocation of memory array failed."); exit(0); } return v; } float **pymatrix_to_carray(pyarrayobject *arrayin) { float **c, *a; int i,n,m; n = pyarray_dim(arrayin, 0); m = pyarray_dim(arrayin, 1); c=_ptrvector(n); = (float*) pyarray_data(arrayin); ( i=0; i<n; i++) { c[i]=a+i*m; } return c; }
i segmentation fault on linux 64 bit machine. problem code works on 32 bit machines (both windows , linux). sizeof(size_t) returns correctly 4 on 32bit machines , 8 on 64bit machines. i'm using python 2.7.1 [epd 7.0-2 (64-bit)] , gcc 4.1.2 on red hat linux 4.2.1-44 kernel version 2.6.18.
i tried npy_intp , py_ssize_t instead of size_t no positive effect.
here want allocate memory pointers float
:
float **v; v=(float **)malloc((size_t) (n*sizeof(float)));
but allocated memory float
s themselfes. on 32bit system pointers need 4 bytes, works.
on 64bit system pointers need 8 byte, might change above line be:
float ** v = malloc(n * sizeof(float*));
or more secure
float ** v = malloc(n * sizeof(*v));
btw: in c not needed caste result of malloc/calloc/realloc
nor recommended. more dangerous might hide awful mistakes.
Comments
Post a Comment