Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mex file is crashing, how to use MATLAB_MEM_MGR in matlab?

I have compiled a c++ code to MEX-file, but on calling this MEX-file, it crashes. It gives the following error message in MATLAB:

Segmentation violation detected

I tried using try-catch in C++ file to print the message in the catch block like,

try {
    //my code;
}
catch(std::exception &e)
{
    mexPrintf(e.what());
    mexEvalString("drawnow;");
    return;
}

but the print message does not work and the code still crashes.

On looking at Google, most of the time it points to some form of message given by MathWorks: http://www.mathworks.de/matlabcentral/newsreader/view_thread/25900

which instructs to set a environment variable "MATLAB_MEM_MGR=debug", but it does not explain how to use it? Can anyone please explain it?

like image 531
abhishek kumar Avatar asked Oct 11 '22 21:10

abhishek kumar


1 Answers

First off, try/catch will not catch a segmentation violation. It only catches C++ exceptions, not signals like sigsegv.

Second, to "use" MATLAB_MEM_MGR:

  1. Set the environment variable MATLAB_MEM_MGR to "debug" in an OS shell (like a Command prompt on Windows or a terminal on Unix),
  2. Run MATLAB from that same shell,
  3. Run your MEX-function normally from that MATLAB.

As Q3.5 of the FAQ says, if the MEX-function corrupts memory by (for example) writing past the end of a MATLAB-allocated block of memory, MATLAB will report the corruption when the block of memory is freed.

You may instead want to try running your MEX-function under a debugger. This tech note has several links describing how to do so on various platforms.

EDIT: previous link is dead, here is the latest doc page.

like image 175
SCFrench Avatar answered Oct 14 '22 04:10

SCFrench