Search code examples
cmemorymex

Why I have memory leak in C/MEX?


I'm totally beginner in C/MEX. This is a simple code for call the "magic" function from MATLAB. I have no idea why I get "Out of memory" message.

#include <mex.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    #define A_IN prhs[0]
    #define A_OUT plhs[0]
    mxArray *R;
    R=mxCreateDoubleMatrix(A_IN,A_IN,mxREAL);
    mexCallMATLAB(1, R, 1, &A_IN, "magic");
    A_OUT = mxDuplicateArray(R);
    mxDestroyArray(R);
    return;
}

Solution

  • A_OUT seems to be a duplicate of R. Basically, according to the doc (that you should read before asking any question, just sayin' :) ), is creating a new array. Calling this function will allocate more memory to store this copy.

    So the leak is from A_OUT. You can use the valgrind tool to help you finding those, with the options --leak-check=full. Of course, compile with the debug flags of your compiler (-g3 for gcc), it will give you most of the informations you need to fix your leaks.