Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mex function memory leak

I am new to writing MEX-functions and I have a memory problem. The MEXf getaway routine is as follows:

void mexFunction (int nlhs, mxArray *plhs[], int nrhs,const mxArray *prhs[]){

double *ecg;                    /*Pointer to double for input data*/
double *outArray;               /*Pointer to double for output data*/
void *dyn;                      /*Pointer to void for the dynamic allocation of memory 
int N=0;
int i=1;
int j=0; 
int k=0;
/*CHECK FOR PROPER NUMBER OF ARGUMENTS*/

if (nrhs != 1 ) mexErrMsgIdAndTxt("EplimitedQRSDetector:NoInput", "This function takes  one input argument: ECG.");
else if(nlhs!=1) mexErrMsgIdAndTxt("EplimitedQRSDetector:NoOutput", "This function requires one output argument.");



/*LOAD INPUT DATA AND ALLOCATE OUTPUT MEMORY*/
ecg=mxGetPr(prhs[0]);                       /*Input data loading*/
N=(int) mxGetM(prhs[0]);                    
plhs[0]=mxCreateDoubleMatrix(0,0,mxREAL); 
dyn = mxCalloc(N,sizeof(double));           /*Dynamic memory allocation*/
outArray=(double*) dyn;                     



/*CALL THE SUBROUTINE*/

for (j=0;j<N;j++){
    outArray[k]=QRSDet(ecg[j], i );         
    if (outArray[k]!=0){ 
        outArray[k]=j-outArray[k];         
        k++;
    }
    i=0;
}


/*FILL THE OUTPUT ARRAY*/

mxSetData(plhs[0], outArray);               
mxSetM(plhs[0], k-1);                       
mxSetN(plhs[0], 1);
mxFree(dyn);
mxFree(outArray);
return;

When I call the Mex-function from the matlab command window, i get the error message "maximum variable size allowed by the function is exceeded". Since the function worked well the first few times i used it, I think the problem is that I don't free memory in the right way in my code. Any suggestions would be greatly appreciated :) Thanks!

N

like image 828
NmilG Avatar asked Mar 16 '26 17:03

NmilG


1 Answers

The code is now running thanks to the modifications suggested by Navan. In addition to the improper use of mxFree, these 3 lines were causing a segmentation violation:

mxSetData(plhs[0], outArray);               
mxSetM(plhs[0], k-1);                       
mxSetN(plhs[0], 1);

outArray is pointing to a Nx1 array allocated using mxCalloc, so setting the first dimension of plhs[0] to (k-1)!=N causes the segmentation violation. Once substituted that line with

mxSetM(plhs[0], N)

the algorithm started to work properly. Thank you for your help.

like image 187
NmilG Avatar answered Mar 18 '26 16:03

NmilG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!