Prevent memory leak when returning from MEX
1 view (last 30 days)
Show older comments
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?
0 Comments
Answers (0)
See Also
Categories
Find more on Write C Functions Callable from MATLAB (MEX Files) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!