justin
justin

Reputation: 183

Freeing memory in mex code

I am writing a mex code and I am thinking that I am not using memory very efficiently. Here is what I do. I am allocating memory for variable called out like

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

plhs[0]=mxCreateDoubleMatrix(1,N,mxREAL);

set(plhs[0],out);

The problem is that I am not freeing memory that I allocate for variable out because if I do I will receive segmentation error since I will use it in Matlab. So can anyone suggest me a better technique to do what above commands are doing ? Is there anyway to free memory for out or to avoid defining matrix of length 1X N?

Thanks.

Upvotes: 0

Views: 212

Answers (1)

Suever
Suever

Reputation: 65460

You don't need to allocate the array with mxMalloc. mxCreateDoubleMatrix already allocates the array. Once you have your pointer to this data (obtained using mxGetPr), you can then fill the array with the necessary values.

double *out;

// Allocate memory for the first output
plhs[0] = mxCreateDoubleMatrix(1,N,mxREAL);

// Get the pointer to the output data
out = mxGetPr(plhs[0]);

// Run your algorithm here to populate out with the data you need

If for some reason you do need to create out in some other way, you want to copy the contents of that separate array into the output prior to freeing the memory.

double *out;
double *realout;

// Allocate data to use internally
out = mxMalloc(sizeof(double) * N);

// Initialize the array that will be returned to MATLAB 
plhs[0] = mxCreateDoubleMatrix(1, N, mxREAL);
realout = mxGetPr(plhs[0]);

// Now copy all values to the MATLAB output
for ( j = 0; j < N; j++ )
    realout[j] = out[j];

// Now you can free up memory for out
mxFree(out)

Upvotes: 2

Related Questions