|
|
Re: matlab/mex function doesn't free memory
Posted:
Apr 8, 2009 11:20 PM
|
|
Praetorian <ashish.sadanandan@gmail.com> wrote in message <251c8005-d072-419f-ad9a-28680bdb1707@g19g2000yql.googlegroups.com>... > > James, > I was hoping you'd see this thread. Take a look at the post from Ronan > on the 4th of February. It was directed to me but I didn't see it > until last night. Do you have any experience with calling a DLL that > uses the mxCreate* functions to allocate memory? And does the MATLAB > memory manager garbage collect that memory assuming that the DLL is > loaded and used by a mex file? > > Regards, > Ashish.
Well, I didn't have any experience with this when I first read this post, but now I do. The answer is no, MATLAB does *not* do garbage collection on mx___ allocated memory in a loaded dll. This is different from mex functions, where garbage collection *is* done. Example files are below. Commands I used to show the memory leak are:
mex mexmem.c mexmem feature memstats
This will show the garbage collection being done for mex functions. Inside the function, 100MB is allocated but not explicitly deallocated. The feature memstats done inside the mex routine show the allocation. But upon returning to MATLAB and doing a feature memstats reveals that the memory is in fact freed.
Now build the dllmem dll (I used a mex command with a custom mexopts.bat file to build the dll library) and then do this:
loadlibrary('dllmem.mexw32','dllmem.h') feature memstats calllib('dllmem','memallocate') feature memstats unloadlibrary('dllmem') feature memstats
You can see that the 100MB has been leaked. Garbage collection did *not* take place when the dll library was unloaded.
Bottom line: Free the memory manually, no safety net here.
James Tursa
-------------------------------------------------------------------------------------------------- mexmem.c
#include "mex.h"
double *dp = NULL;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mexEvalString("feature memstats"); if( dp == NULL ) { dp = mxMalloc(13107200*sizeof(double)); // allocate 100MB } mexEvalString("feature memstats"); }
------------------------------------------------------------------------------------------------------- dllmem.c
#include "mex.h"
double *dp = NULL;
void memallocate(void) { if( dp == NULL ) { dp = mxMalloc(13107200*sizeof(double)); // allocate 100MB } }
void memdeallocate(void) { if( dp ) { mxFree(dp); } dp = NULL; }
----------------------------------------------------------------------------------------------------- dllmem.h
void memallocate(void); void memdeallocate(void);
---------------------------------------------------------------------------------------------------- dllmem.def
EXPORTS memallocate memdeallocate
|
|