Prevent memory leak when returning from MEX

1 visualización (últimos 30 días)
Gabe Hopper
Gabe Hopper el 4 de Feb. de 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?

Respuestas (0)

Categorías

Más información sobre Write C Functions Callable from MATLAB (MEX Files) en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by