Background: I'm writing a mex that needs to work with a large amount of data in batches. In order to avoid having to wrap a c++ object in a handle object, I'm instead executing a Matlab callback for each iteration (essentially option 2 from Oliver's initial post here). I've isolated my problem to a testcase (see below) that produces random segmentation faults. At first I thought it was related to an improper mxDestroyArray but now I'm not freeing anything! Rather the issue appears to be related to the repeated use of a handle to a nested function. I get similar crashes when using an anonymous function handle. If I make it scoped however, it seems to be ok, likewise if I store the handle in a global and use a regular function to trampoline.
I've also tried mxDuplicateArray-ing the callback before each use, in-case there was some overzealous memory re-claiming, but that didn't help.
Note that it usually works correctly on the first run - if I then edit say the string that gets displayed in the callback and re-run, it will then crash.
I'm using Matlab 2012b and VS2010.
testcasemex.cpp :
#include "mex.h"
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
if (nrhs != 1 || !mxIsClass(prhs[0],"function_handle"))
mexErrMsgTxt("Expected function handle.");
for (int i = 0; i < 20; i++) {
mxArray *arrays = mxCreateCellMatrix(1, 10);
for (int j = 0; j < 10; j++)
mxSetCell(arrays, j, mxCreateNumericMatrix(1000, 1000, mxUINT32_CLASS, mxREAL));
mxArray *args[] = {(mxArray *)prhs[0], arrays};
mexCallMATLAB(0, nullptr, 2, args, "feval");
}
}
testcase.m :
function testcase
counter = 1;
function callback(array)
counter = counter + 1;
disp('In callback')
size(array)
pause(0.1)
end
testcasemex(@callback);
end