Prevent memory leak when returning from MEX

조회 수: 3 (최근 30일)
Gabe Hopper
Gabe Hopper 2018년 2월 4일
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개)

카테고리

Help CenterFile Exchange에서 MATLAB Compiler SDK에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by