Prevent memory leak when returning from MEX

1 Ansicht (letzte 30 Tage)
Gabe Hopper
Gabe Hopper am 4 Feb. 2018
Dear all,
I have the following code in a C file (using the MEX Gateway):
double *result;
Sim simulation(prhs, nrhs);
simulation.run(result);
...
plhs[0] = mxCreateDoubleMatrix(100, 2, mxREAL);
std::memcpy(mxGetPr(plhs[0]), result, 2 * 100 * sizeof(double));
variable 'result' contains the adress of another double* that contains a 2D array with all results, ie:
void Sim::run(double *(&res)) {
time_N = (double *) malloc(2 * 100 * sizeof(double));
...
res = time_N; //assign result to output.
}
and the array time_N is freed in the distructor of Sim:
Sim::~Sim()
{
free(time_N); //output vector.
}
Then I copy result into plhs[0]. This code compile and works perfectly, but I assume there is a memory leak somewhere because 'result' is not freed anywhere and the memory is dumped to plhs. Is that correct? How to overcome this issue?

Antworten (0)

Kategorien

Mehr zu Write C Functions Callable from MATLAB (MEX Files) finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by