I have a C mex file that runs correctly, but MATLAB crashes with segfault after it executes. Since it crashes after the program ends, it makes me think that automatically freeing the allocated MATLAB memory is causing a problem. However, I am freeing my dynamically allocated variables and not trying to free up the mxArray structures. Please look and see if you can help me determine why this causes MATLAB to crash.
#include <mex.h> #include <matrix.h> #include <stdio.h> void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Declare variables. */ int i ,j, numdims, *ipos, count; const mwSize *dim_array; mwSize size; double *pos, rad; /* Ingest inputs. */ numdims = mxGetNumberOfDimensions(prhs[0]); dim_array = mxGetDimensions(prhs[0]); rad = mxGetScalar(prhs[1]); pos = mxGetData(prhs[0]); size = dim_array[0]*dim_array[1]; ipos = (int*) mxMalloc(size); for (i = 0; i < size; i++) ipos[i] = (int) (pos[i]*rad); count = 0; for (i = 0; i < size; i+=2) for (j = i + 2; j < size; j+=2) if (ipos[i] == ipos[j]) if (ipos[i+1] == ipos[j+1]) count++; mxFree(ipos); /* Generate output */ plhs[0] = mxCreateDoubleScalar(count); printf("\nProgram finished executing!\n"); }
Thanks in advance for your help!
Edit: I should also note that program entries should be (in order) a 2 xn matrix and a scalar, where n can be any positive integer. The actual program correctly checks the sizes, but I did not use these lines to save code space.
source share