Strange problem with memory management in MEX
조회 수: 7 (최근 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
댓글 수: 0
답변 (1개)
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 MATLAB Compiler SDK에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!