Troubleshooting

Configuration Issues

This section focuses on common problems that might occur when creating binary MEX-files.

Search Path Problem on Microsoft® Windows® Systems

On Windows® systems, if you move the MATLAB® executable without reinstalling the MATLAB software, you may need to modify mex.bat to point to the new MATLAB location.

MATLAB® Path Names Containing Spaces on Windows® Systems

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 may have difficulty building MEX-files with certain C compilers.

DLL Files Not on Path on Microsoft®Windows® Systems

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 this problem. 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

Internal Error When Using mex -setup ()

Some antivirus software packages may 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.

General Configuration Problem

Make sure you followed the configuration steps for your platform described in this chapter. Also, refer to Custom Building Binary MEX-Files for additional information.

Understanding MEX-File Problems

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

Flowchart illustrating common MEX-file creation problems and their solutions

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

Problem 1 — Compiling a Source MEX-File Fails

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 Binary MEX-Files for information on selecting the appropriate options file or, if necessary, obtain an ANSI C compiler.

Problem 2 — Compiling Your Own Program Fails

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 Compiler Requirements for this information. Additional information can be found in Compiler and Platform-Specific Issues.

Problem 3 — Binary MEX-File Load Errors

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 may 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.

Problem 4 — Segmentation Fault or Bus Error

If your binary MEX-file causes a segmentation violation or bus error, it means the MEX-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 may 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 three features to help you troubleshoot problems of this nature. Listed in order of simplicity, they are as follows:

Problem 5 - Program Generates Incorrect Results

If your program generates the wrong answer(s), there are several possible 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.

Compiler and Platform-Specific Issues

This section describes situations specific to particular compilers and platforms.

Using Binary MEX-Files from Other Sources

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.

Linux® gcc Compiler Version Error

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

Fortran Source MEX-Files Compiler Errors

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

Binary MEX-Files Created in Watcom IDE

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.

Memory Management Issues

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:

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:

Improperly Destroying an mxArray

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 */

Incorrectly Constructing a Cell or Structure mxArray

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 */

Creating a Temporary mxArray with Improper Data

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 */

Creating Potential Memory Leaks

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.

Improperly Destroying a Structure

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); 

Destroying Memory in a C++ Class Destructor

Do not use the mxFree or mxDestroyArray functions in a C++ destructor of a class used in a MEX-function. MATLAB performs cleanup of MEX-file variables if an error is thrown from the MEX-function, as described in Automatic Cleanup of Temporary Arrays.

If an error occurs that causes the object to go out of scope, the C++ destructor is called. Freeing memory directly in the destructor means both MATLAB and the destructor free the same memory, and this corrupts memory.


[1] UNIX is a registered trademark of The Open Group in the United States and other countries.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS