Why does my C MEX-file, with large locally-scoped variables, generate a segmentation fault in MATLAB?

1 view (last 30 days)
I have created a C MEX-file that uses large locally-scoped arrays or structures, or uses a recursive algorithm. When I try to run my MEX-file from the MATLAB command line, MATLAB immediately terminates.
A run-time error may be generated before MATLAB crashes, depending both on the current platform and the compiler used to generate the MEX-file.
On a Windows platform using the lcc compiler that is distributed with MATLAB, the following message is generated before MATLAB crashes:
Runtime error!
Program D:\Applications\MATLAB704\bin\win32\MATLAB.exe
The application has requested the runtime to terminate it in an unusual way. Please contact the application's support team for more information.
On a Windows platform using the Microsoft Visual C++ compiler, the following message is generated and MATLAB does not crash:
??? Unknown Windows exception value=c00000fd in MATLAB.
On a Red Hat Linux platform using the gcc compiler, the following message is generated before MATLAB terminates:
Segmentation fault (core dumped)

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
This situation is commonly referred to as "stack overflow."
The memory for a variable declared local to a function is automatically allocated (i.e., at run time) by the compiler on the program's call stack. Operating systems impose a maximum size for the call stack, which will vary depending on the operating system. When a program's stack size exceeds this limit, the program will terminate.
The most common causes of stack overflow are infinite or very deep recursion, and large local objects. If a MEX-file function utilizes large data structures or arrays, these should be dynamically allocated in MATLAB's free store (also known as the "heap") using the mxMalloc/mxCalloc functions. Memory allocated dynamically in this way must then be deallocated using the mxFree function.
For more information on these functions, see the C MX-Functions reference page, which can be viewed by copying the following to the MATLAB command prompt:
web([docroot,'/techdoc/apiref/mx-c.html'])

More Answers (0)

Categories

Find more on MATLAB Compiler in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!