Why do I receive a segmentation violation when I run a C-MEX file or Fortran MEX file that I compiled?

I have created a C-MEX file or Fortran MEX file that compiles successfully using the MEX command. When I run this MEX-function from the MATLAB command prompt, MATLAB issues a segmentation violation and stack trace.

"This error was detected while a MEX-file was running. If the MEX-file is not an official MathWorks function, please examine its source code for errors. Please consult the External Interfaces Guide for information on debugging MEX-files."

Before MathWorks can provide assistance with this issue, you will need to determine where the problem is within your code by debugging it. Most likely, an attempt has been made to write to unallocated memory, or memory is destroyed that is later used by MATLAB.

One debugging technique that may be helpful is to run MATLAB in check_malloc mode. When run in this mode, MATLAB attaches a header and footer to each block of allocated memory. This information can then be used to determine if an attempt is made to write to unallocated memory. Note that, in general, MATLAB will run slower when in check_malloc mode.

For more information on running MATLAB in check_malloc mode, see the Related Solution listed below:

Additionally, be sure to use mxMalloc in your code for any memory that is dynamically created and be sure not to use mxFree on any data returned to MATLAB. See the following URLs for more information on these functions:

Another common error is filling an mxArray in an improper manner. The Related Solution listed below shows four correct methods for filling an mxArray.

Another helpful debugging technique is to include mexPrintf functions periodically in your code. This technique can ultimately be used to determine the line of code that is generating the segmentation violation. By examining the history of pointers used on the offending line, one can determine where they went awry.