C++ Mex File Clear All Memory and Dynamic Memory

5 次查看(过去 30 天)
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