C++ Mex File Clear All Memory and Dynamic Memory

조회 수: 4 (최근 30일)
Kevin
Kevin 2012년 3월 20일
I have a C++ mex file that takes a raw data signal of varying length as an input. I noticed a memory leak and I believe it is due to not clearing the dynamic memory such as 'rawdata'. I pasted a gutted outline of the code I am using below.
When I try to delete 'rawdata' as shown below, it crashes Matlab. Does anyone have any recommendations of how I should clear the variable 'rawdata'?
Better yet, is there a command to clear all variables from memory after a mex function runs to completion? (Such as the matlab 'clear all') Is there a way to better trouble shoot a memory leak and determine which variable it is coming from?
void main(double *rawdata) { delete[] rawdata; rawdata = 0x0; }
/* The gateway function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
double *rawdata;
rawdata = mxGetPr(prhs[0]);
/* assign a pointer to the output */
main(rawdata);
}

채택된 답변

James Tursa
James Tursa 2012년 3월 20일
Yeah, that's going to crash for sure. A couple of things:
1) prhs[0] is a read-only input. You should not be trying to free anything associated with prhs[0].
2) mxGetPr returns a pointer to memory that was allocated with the MATLAB memory manager. You should never try to free up this memory with any native C/C++ method such as free or delete. You can only use mxFree for this (or mxDestroyArray for mxArray variables), and then only if the memory in question is temporary memory that was allocated by you inside the mex routine itself.
3) Even putting 1 and 2 aside, and even if the delete[] was used properly, rawdata is passed in by value to main ... setting it to 0x0 inside main does nothing to the original variable that was passed in. I.e., this won't change rawdata to 0x0 inside mexFunction. This is a basic C/C++ programming mistake.
Regarding your apparent memory leak, we don't have enough to go on. You will have to show more code.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Write C Functions Callable from MATLAB (MEX Files)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by