Debugging a MEX file requires the MEX source files (usually C/C++). If you are not the author of the MEX file, please contact the author for assistance or to obtain the source code for troubleshooting.
If you are the author or have access to the source code, you can investigate the issue on your own. Below are some resources that may be helpful when troubleshooting MEX file issues, such as MATLAB crashes or runtime errors or warnings.
Debugging C/C++ MEX Source Files:
The following tools and instructions are available for debugging C/C++ MEX source files depending on your platform:
Out-Of-Process Execution For C++ MEX Functions:
Please note that this feature is available only for C++ MEX functions and cannot be used with C MEX functions. It is also unavailable for S-functions.
Common Causes of MEX Issues:
Some common causes of MEX issues are the following:
- Memory Management Issues: Improper memory handling can cause MATLAB to crash. Always use MATLAB's mx* routines for memory allocation, such as mxCreate* and mxMalloc. Ensure that you free any allocated memory using mxFree.
- Input/Output Argument Errors: Ensure that your code checks for the correct number of input and output arguments. Accessing non-existent mxArray elements can lead to crashes (e.g. prhs[1], and MEX file is called with 0 or 1 input argument).
- Improper Indexing: Avoid indexing into cleared or invalid arrays. Always check the dimensions of arrays before accessing their elements.
- Version Compatibility: Ensure the MEX source code is compatible with your current version of MATLAB and that is was re-compiled. Refer to the Build C MEX Programs and Build C++ MEX Programs documentation for guidance. If unsure about the options used, consult the MEX documentation for available compilation options.
References and Examples for Writing C/C++ MEX functions:
Review the following pages for an overview and examples:
Debugging Other MEX Languages and Workflows:
The following instructions are available for debugging other types of MEX functions:
Further Troubleshooting
Unfortunately, debugging issues related to custom MEX files falls outside the scope of MathWorks Technical Support.
If you are unable to utilize the information in the documentation to troubleshoot your custom MEX function, you can contact MathWorks Technical Support for help using the available resources for you to troubleshoot your MEX function. Note that Technical Support can provide guidance on MEX setup issues, compilers, and library dependencies and give general best practices for MEX function creation and debugging only.