| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
| On this page… |
|---|
Understanding MEX-File Problems |
This section focuses on common problems that might occur when creating binary MEX-files.
On Windows systems, if you move the MATLAB executable without reinstalling the MATLAB software, you might need to modify mex.bat to point to the new MATLAB location.
If you have problems building MEX-files on Windows systems and there is a space in any of the directory names within the MATLAB path, either reinstall MATLAB into a path name that contains no spaces or rename the directory that contains the space. For example, if you install MATLAB under the Program Files directory, you might have difficulty building MEX-files with certain C compilers.
MATLAB fails to load binary MEX-files if it cannot find all .dll files referenced by the MEX-file; the .dll files must be on the DOS path or in the same directory as the MEX-file. This is also true for third-party .dll files.
When this happens, MATLAB displays an error message of the following form:
??? Invalid MEX-file <mexfilename>: The specified module could not be found.
On Windows systems, the third-party product Dependency Walker can be used to diagnose errors related to loading and executing modules. Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module and builds a hierarchical tree diagram of all dependent modules. For each module found, it lists all the functions that are exported by that module, and which of those functions are actually being called by other modules. You can download the Dependency Walker utility from the following Web site:
http://www.dependencywalker.com/
See the Technical Support solution 1-2RQL4L for information on using the Dependency Walker:
http://www.mathworks.com/support/solutions/data/1-2RQL4L.html
Some antivirus software packages might conflict with the mex -setup process or other mex commands. If you get an error message of the following form in response to a mex command:
mex.bat: internal error in sub get_compiler_info(): don't recognize <string>
then you need to disable your antivirus software temporarily and reenter the command. After you have successfully run the mex script, you can reenable your antivirus software.
Alternatively, you can open a separate MS-DOS window and enter the mex command from that window.
Make sure you followed the configuration steps for your platform described in this chapter. Also, refer to Custom Building MEX-Files for additional information.
This section contains information regarding common problems that occur when creating binary MEX-files. Use the following figure to help isolate these problems.
Troubleshooting MEX-File Creation Problems

Problems 1 through 5 refer to the corresponding numbered sections of the previous flowchart. For additional suggestions on resolving MEX-file build problems, access The MathWorks Technical Support Web site at:
http://www.mathworks.com/support
The most common configuration problem in creating C source MEX-files on UNIX[1] systems involves using a non-ANSI C compiler, or failing to pass to the compiler a flag that tells it to compile ANSI C code.
A reliable way of knowing if you have this type of configuration problem is if the header files supplied by MATLAB generate a string of syntax errors when you try to compile your code. See Building MEX-Files for information on selecting the appropriate options file or, if necessary, obtain an ANSI C compiler.
Mixing ANSI and non-ANSI C code can generate a string of syntax errors. MATLAB provides header and source files that are ANSI C compliant. Therefore, your C code must also be ANSI compliant.
Other common problems that can occur in any C program are neglecting to include all necessary header files, or neglecting to link against all required libraries.
Make sure you are using a MATLAB-supported compiler. See What You Need to Build MEX-Files for this information. Additional information can be found in Compiler and Platform-Specific Issues.
If you receive an error of the form:
Unable to load mex file: ??? Invalid MEX-file
MATLAB does not recognize your MEX-file.
MATLAB loads MEX-files by looking for the gateway routine, mexFunction. If you misspell the function name, MATLAB cannot load your MEX-file and generates an error message. On Windows systems, check that you are exporting mexFunction correctly.
On some platforms, if you fail to link against required libraries, you might get an error when MATLAB loads your MEX-file rather than when you compile your MEX-file. In such cases, a system error message referring to unresolved symbols or unresolved references appears. Be sure to link against the library that defines the function in question.
On Windows systems, MATLAB fails to load MEX-files if it cannot find all .dll files referenced by the MEX-file; the .dll files must be on the path or in the same directory as the MEX-file. This is also true for third-party .dll files. See DLL Files Not on Path on Microsoft Windows Systems for information to diagnose this problem.
If a binary MEX-file causes a segmentation violation or bus error, it means theMEX-file has attempted to access protected, read-only, or unallocated memory. Since this is such a general category of programming errors, such problems are sometimes difficult to track down.
Segmentation violations do not always occur at the same point as the logical errors that cause them. If a program writes data to an unintended section of memory, an error might not occur until the program reads and interprets the corrupted data. Consequently, a segmentation violation or bus error can occur after the MEX-file finishes executing.
MATLAB provides the following features to help you troubleshoot problems of this nature:
Recompile your source MEX-file with argument checking (C MEX-files only). You can add a layer of error checking to your MEX-file by recompiling with the mex script flag -argcheck. This warns you about invalid arguments to both MATLAB MEX-file (mex) and matrix access (mx) API functions.
Although your MEX-file will not run as efficiently as it can, this switch detects errors such as passing null pointers to API functions.
Run MATLAB within a debugging environment. This process is already described in the chapters on creating C and Fortran source MEX-files, respectively.
If your program generates the wrong answer(s), there are several causes. First, there could be an error in the computational logic. Second, the program could be reading from an uninitialized section of memory. For example, reading the 11th element of a 10-element vector yields unpredictable results.
Another cause of generating a wrong answer could be overwriting valid data due to memory mishandling. For example, writing to the 15th element of a 10-element vector might overwrite data in the adjacent variable in memory. This case can be handled in a similar manner as segmentation violations, as described in Problem 4.
In all of these cases, you can use mexPrintf to examine data values at intermediate stages or run MATLAB within a debugger to exploit all the tools the debugger provides.
This section describes situations specific to particular compilers and platforms.
If you obtain a binary MEX-file from another source, be sure the file was compiled for the same platform on which you want to run it. See What Are MEX-Files? for platform-specific information.
When you try to run a binary MEX-file from a version of MATLAB that is different from the version that created the MEX-file, MATLAB displays an error message of the following form:
??? Invalid MEX-file <mexfilename>: The specified module could not be found.
For information concerning a gcc compiler version error on Linux systems, see the Technical Support solution 1-2H64MF at:
http://www.mathworks.com/support/solutions/data/1-2H64MF.html
When you try to compile a Fortran MEX-file using a free source form format, MATLAB displays an error message of the following form:
Illegal character in statement label field
mex supports the fixed source form. The difference between free and fixed source forms is explained in the Fortran Language Reference Manual Source Forms topic. The URL for this topic is:
http://h21007.www2.hp.com/portal/download/files/unprot/Fortran/ docs/lrm/lrm0015.htm#source_formatmenu?&Record=383697&STASH=7
The URL for the Fortran Language Reference Manual is:
http://h21007.www2.hp.com/portal/download/files/unprot/Fortran/ docs/lrm/dflrm.htm
If you use the Watcom IDE to create MEX-files and get unresolved references to API functions when linking against our libraries, check the argument-passing convention. The Watcom IDE uses a default switch that passes parameters in registers. MATLAB requires that you pass parameters on the stack.
When a binary MEX-file returns control to MATLAB, it returns the results of its computations in the output arguments—the mxArrays contained in the left-hand side arguments plhs[]. MATLAB destroys any mxArray created by the MEX-file that is not in this argument list. In addition, MATLAB frees any memory that was allocated in the MEX-file using the mxCalloc, mxMalloc, or mxRealloc functions.
In general, we recommend that MEX-file functions destroy their own temporary arrays and free their own dynamically allocated memory. It is more efficient to perform this cleanup in the source MEX-file than to rely on the automatic mechanism. This approach is consistent with other MATLAB API applications (i.e., MAT-file applications, engine applications, and MATLAB® Compiler™ generated applications, which do not have any automatic cleanup mechanism.)
However, you should not destroy an mxArray in a source MEX-file when it is:
passed to the MEX-file in the right-hand side list prhs[]
returned in the left-hand side list plhs[]
returned by mexGetVariablePtr
used to create a structure
This section describes situations specific to memory management. We recommend you review code in your source MEX-files to avoid using these functions in the following situations. For additional information, see Memory Management in Creating C Language MEX-Files. For guidance on memory issues, see Strategies for Efficient Use of Memory. Additional tips are found in Technical Note 1107: "Avoiding Out of Memory Errors" at the following URL:
http://www.mathworks.com/support/tech-notes/1100/1107.html.
Potential memory management problems include:
Do not use mxFree to destroy an mxArray.
Example. In the following example, mxFree does not destroy the array object. This operation frees the structure header associated with the array, but MATLAB stills operates as if the array object needs to be destroyed. Thus MATLAB tries to destroy the array object, and in the process, attempts to free its structure header again:
mxArray *temp = mxCreateDoubleMatrix(1,1,mxREAL);
...
mxFree(temp); /* INCORRECT */Solution. Call mxDestroyArray instead:
mxDestroyArray(temp); /* CORRECT */
Do not call mxSetCell or mxSetField variants with prhs[] as the member array.
Example. In the following example, when the MEX-file returns, MATLAB destroys the entire cell array. Since this includes the members of the cell, this implicitly destroys the MEX-file's input arguments. This can cause several strange results, generally having to do with the corruption of the caller's workspace, if the right-hand side argument used is a temporary array (i.e., a literal or the result of an expression):
myfunction('hello')
/* myfunction is the name of your MEX-file and your code
/* contains the following: */
mxArray *temp = mxCreateCellMatrix(1,1);
...
mxSetCell(temp, 0, prhs[0]); /* INCORRECT */Solution. Make a copy of the right-hand side argument with mxDuplicateArray and use that copy as the argument to mxSetCell (or mxSetField variants). For example:
mxSetCell(temp, 0, mxDuplicateArray(prhs[0])); /* CORRECT */
Do not call mxDestroyArray on an mxArray whose data was not allocated by an API routine.
Example. If you call mxSetPr, mxSetPi, mxSetData, or mxSetImagData, specifying memory that was not allocated by mxCalloc, mxMalloc, or mxRealloc as the intended data block (second argument), then when the MEX-file returns, MATLAB attempts to free the pointers to real data and imaginary data (if any). Thus MATLAB attempts to free memory, in this example, from the program stack:
mxArray *temp = mxCreateDoubleMatrix(0,0,mxREAL);
double data[5] = {1,2,3,4,5};
...
mxSetM(temp,1); mxSetN(temp,5); mxSetPr(temp, data);
/* INCORRECT */Solution. Rather than use mxSetPr to set the data pointer, instead, create the mxArray with the right size and use memcpy to copy the stack data into the buffer returned by mxGetPr:
mxArray *temp = mxCreateDoubleMatrix(1,5,mxREAL);
double data[5] = {1,2,3,4,5};
...
memcpy(mxGetPr(temp), data, 5*sizeof(double)); /* CORRECT */Prior to Version 5.2, if you created an mxArray using one of the API creation routines and then you overwrote the pointer to the data using mxSetPr, MATLAB still freed the original memory. This is no longer the case.
For example:
pr = mxCalloc(5*5, sizeof(double)); ... <load data into pr> plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL); mxSetPr(plhs[0], pr); /* INCORRECT */
will now leak 5*5*8 bytes of memory, where 8 bytes is the size of a double.
You can avoid that memory leak by changing the code to:
plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL); pr = mxGetPr(plhs[0]); ... <load data into pr>
or alternatively:
pr = mxCalloc(5*5, sizeof(double)); ... <load data into pr> plhs[0] = mxCreateDoubleMatrix(5,5,mxREAL); mxFree(mxGetPr(plhs[0])); mxSetPr(plhs[0], pr);
Note that the first solution is more efficient.
Similar memory leaks can also occur when using mxSetPi, mxSetData, mxSetImagData, mxSetIr, or mxSetJc. You can avoid memory leaks by changing the code as described in this section.
If you create a structure, you must call mxDestroyArray only on the structure. A field in the structure points to the data in the array used by mxSetField or mxSetFieldByNumber. When mxDestroyArray destroys the structure, it attempts to traverse down through itself and free all other data, including the memory in the data arrays. If you call mxDestroyArray on each data array, the same memory is freed twice and this can corrupt memory.
Example. The following example creates three arrays: one structure array aStruct and two data arrays, myDataOne and myDataTwo. Field name one contains a pointer to the data in myDataOne, and field name two contains a pointer to the data in myDataTwo.
mxArray *myDataOne;
mxArray *myDataTwo;
mxArray *aStruct;
const char *fields[] = { "one", "two" };
myDataOne = mxCreateDoubleScalar(1.0);
myDataTwo = mxCreateDoubleScalar(2.0);
aStruct = mxCreateStructMatrix(1,1,2,fields);
mxSetField( aStruct, 0, "one", myDataOne );
mxSetField( aStruct, 1, "two", myDataTwo );
mxDestroyArray(myDataOne);
mxDestroyArray(myDataTwo);
mxDestroyArray(aStruct);
Solution. The command mxDestroyArray(aStruct) destroys the data in all three arrays:
... aStruct = mxCreateStructMatrix(1,1,2,fields); mxSetField( aStruct, 0, "one", myDataOne ); mxSetField( aStruct, 1, "two", myDataTwo ); mxDestroyArray(aStruct);
Do not use the mxFree or mxDestroyArray functions in a C++ destructor of a class used in a MEX-function. If the MEX-function throws an error, MATLAB cleans up MEX-file variables, as described in Automatic Cleanup of Temporary Arrays.
If an error occurs that causes the object to go out of scope, MATLAB calls the C++ destructor. Freeing memory directly in the destructor means both MATLAB and the destructor free the same memory, which can corrupt memory.
[1] UNIX is a registered trademark of The Open Group in the United States and other countries.
![]() | Custom Building MEX-Files | Additional Information for Using MEX-Files | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2009- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |