Open sg-s opened 5 years ago
it looks like global variables persist across multiple calls to the binary -- need to wait for Mathworks support to clarify behaviour.
apparently global variables do persist. interesting.
If a variable is instantiated inside of a function and marked as global, it should persist in the workspace. What's surprising to me is that this behavior applies to mex functions too.
The workaround is manual garbage collection at the end of each iteration of a loop.
The behaviour is stranger than you imagine:
#include "mex.h"
int wow = 0;
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
void testfunc(void);
for (int i = 0; i < 1e3; i ++) {testfunc();}
mexPrintf("wow = %i\n",wow);
}
void testfunc() {
wow++;
}
I compile it with mex. Now, calling it multiple times gives the following output:
wow = 1000
wow = 2000
wow = 3000
showing that the global variable "wow" persists across function calls. (where??)
Calling "clear mex" resets the counter
clear mex
wow = 1000
wtf
apparently this is expected behaviour according to mathworks support
this is what they had to say:
"mexMakeMemoryPersistent" only applies to memory allocated by MATLAB memory allocation routines such as "mxCalloc", "mxMalloc", "mxRealloc", and the different "mxCreate*" functions (https://www.mathworks.com/help/matlab/create-or-delete-array.html). Global variables in C++ are initialized only once during compilation. The value will persist across subsequent execution of the code, which is why the variable "wow" is increasing in value every time your function is being called. To clear global variables, you can just call clear mex as you have done before. MathWorks does not actively discourage the usage of global variables in MEX files. However, it is up to the developer to exercise caution and keep track of global variables since every function has access to them. Global variables should not cause memory leaks as they are not dynamically allocated. They will reside in the same memory space across subsequent program execution.
Stale issue message
mexFunction