Search code examples
cmatlabmemorymallocmex

When to free allocated memory in mex file


I have some questions about mxMalloc and mxFree for allocating memory in mex code. Assume I am converting C code to Matlab and I allocate memory like this:

in= mxMalloc(sizeof(double)*N);

in =mxGetPr(prhs[0]);

However when later on I free the memory using

 mxFree(in) 

I receive segmentation violation error. I wonder can `anyone explain when I should realize I should free and allocate the memory. what type of pointers should be freed and what type should not be freed?


Solution

  • There are a few issues here. First of all you allocate memory and have the pointer in point to this fresh data.

    in = mxMalloc(sizeof(double)*N);
    

    This is completely unnecessary since you then abandon this data, and instead have the pointer in point to one of the inputs that MATLAB provides to your function.

    in = mxGetPr(prhs[0]);
    

    in now refers to data that MATLAB has provided to your function and MATLAB expects this data to remain there. If you call mxFree to free it up, MATLAB then is unable to access this data when it attempts to access it later causing your segmentation violation error.

    If you hadn't re-assigned in to point to the input data, you could use mxFree to free it up only if you do not plan on passing a pointer to that data back to MATLAB.

    in = mxMalloc(sizeof(double) * N);
    mxFree(in);