Strange problem with memory management in MEX

13 次查看(过去 30 天)
Please help! I've write the following code:
#include <math.h>
#include <stdio.h>
#include "matrix.h"
#include "mex.h"
#include <stdlib.h>
#include <time.h>
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
double *mxTime, *mxStates,*BlockLens;
int nBlocks=10;
int MaxNumOfPercepts=24;
mxTime=(double*)mxCalloc(nBlocks*MaxNumOfPercepts, sizeof(double));
mxTime=(double*)mxGetData(prhs[0]);
mxStates=(double*)mxCalloc(nBlocks*MaxNumOfPercepts, sizeof(double));
mxStates=(double*)mxGetData(prhs[1]);
BlockLens=(double*)mxCalloc(nBlocks*MaxNumOfPercepts, sizeof(double));
BlockLens=(double*)mxGetData(prhs[2]);
mxFree((void*)mxTime);
//mxFree((void*)mxStates);
mxFree((void*)BlockLens);
return;
}
It works well, but if i uncomment deletion of mxState - everzthing crashes. I could not understand the reason. What the diferences between mxTime and mxStates variables? Thank You in advance

回答(1 个)

Geoff Hayes
Geoff Hayes 2015-2-7
Stepan - if I try to run the same code (OS X 10.8.5, R2014a) it crashes unless I comment out all of the mxFree commands.
For each variable you allocate some memory, call mxGetData, and then try to free the memory. But look at the documentation for mxCalloc and mxGetData. It states that the former returns a pointer to the start of the allocated dynamic memory and the latter returns a pointer to the first element of the real data. So in the above code,
mxTime=(double*)mxCalloc(nBlocks*MaxNumOfPercepts, sizeof(double));
mxTime=(double*)mxGetData(prhs[0]);
mxTime initially points to the start of the allocated dynamic memory (because of mxCalloc) and then it points to the first element of real data from prhs[0] (because of mxGetData). So you've "lost" the pointer to the allocated dynamic memory and the mxFree tries to free memory associated with the input prhs[0] and not that which you had allocated (memory leak!).
The software is crashing because the code is trying to free memory to the input variables (which you cannot do) and is not freeing the allocated memory.
Just remove the mxCalloc and mxFree statements and you should be able to build and run the program without any problems.

类别

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