MATLAB: Mex file crash after many run

crashiterationMATLABmemorymex

Hi,
I have a mex function which I am using in a loop. After many iterations matlab gives access violation error and crashes. When I did a little search I found out that it may be resulting from memory allocation. Is there any way to define inputs and outputs differently that I will not get this crash problem? Or should I search for the solution somewhere else in the c code?
Thank you.
Ezgi Köker
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
const mxArray *prhs[])
{
double *altsin, *ustsin,
*altkis, *ustkis,
*xx, *xi, *fonk,
*afr, *mrg, *y, *x, *qs, lo;
long *ndeg, *lver,
*gedeg, edeg, ferti, kac,
nx, ny, nyi, amac;
int a, b;
int sonuc;
int carpan=0,i;
/* Defining inputs */
nx = mxGetScalar(prhs[0]);
ny = mxGetScalar(prhs[1]);
nyi = mxGetScalar(prhs[2]);
amac = mxGetScalar(prhs[3]);
ndeg = mxGetData(prhs[4]);
altsin = mxGetPr(prhs[5]);
ustsin = mxGetPr(prhs[6]);
altkis = mxGetPr(prhs[7]);
ustkis = mxGetPr(prhs[8]);
xi = mxGetPr(prhs[9]);
lo = mxGetScalar(prhs[10]);
a = (int)nvars_in+1;
b = (int)nfun_in+1;
/* Defining outputs */
plhs[0] = mxCreateDoubleMatrix(1,a, mxREAL);
xx = mxGetPr(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(1,b, mxREAL);
fonk = mxGetPr(plhs[1]);
plhs[2] = mxCreateDoubleMatrix(1,b, mxREAL);
afr = mxGetPr(plhs[2]);
plhs[3] = mxCreateDoubleMatrix(1,b, mxREAL);
mrg = mxGetPr(plhs[3]);
plhs[4] = mxCreateNumericMatrix(1,a, mxUINT32_CLASS, mxREAL);
lver = mxGetData(plhs[4]);
plhs[5] =mxCreateNumericMatrix(1,b, mxUINT32_CLASS, mxREAL);
gedeg = mxGetData(plhs[5]);
plhs[6] =mxCreateDoubleMatrix(1,1, mxREAL);
qs = mxGetPr(plhs[6]);
sevket( nx, ny, nyi, amac,
ndeg, altsin, ustsin, altkis, ustkis,
xx, xi, fonk, mrg, lver,
redgr, gedeg, edeg, ferti, kac,
carpan, sonuc, sonuc, a, b, qs, lo);
}

Best Answer

Do not use a long to catch the output of mxGetScalar, which replies a double. int is not a good choice also for a and b, when the documentation explains clearly, that mxCreateDoubleMatrix expects an mwSize.
It is much safer to specify the wanted data type directly using int64_T or mwSize, size_t etc. Letting the compiler decide which data type to use4, is a fragile method. E.g.:
long *ndeg
ndeg = mxGetData(prhs[4]);
If prhs[4] is a int32, use:
int32_T *ndeg
if (!mxIsInt32(prhs[4])) {
mexErrMsgIdAndTxt("YourFunc:BadInput:In5", "5th input must be an INT32");
}
ndeg = (int32_T *) mxGetData(prhs[4]);
But I guess boldly, that the problem is hidden inside sevget. Perhaps you access unallocated memory. Start with cleaning the types and then test the code again exhaustively.