MATLAB: Do I get errors when running generated C code with large inputs in MATLAB Coder 2.0 (R2011a)

matlab coder

I am able to generate C code from my MATLAB file without any problems with MATLAB Coder. When I compile the C code into a MEX file and run it with small inputs, it works fine. However, when I do it with large inputs, I get the following error message:
Severe:
MATLAB has attempted to use more stack space than is available. If a mex
file was in use check for large local variables or infinite recursion.???
Unexpected MATLAB exception.

Best Answer

This error is likely due to a stack overflow. The stack in a running program contains the input and local variables, among other things. If the input variables are too large, the stack will exceed its maximum size, causing this error message.
To work around this problem, push all the data off the stack and onto the heap. For that,
you need to do 2 things:
1) Make your arrays variable-size
2) Turn on the "dynamic memory allocation" feature in CODEGEN. The following code will do this:
cfg = emlcoder.CompilerOptions;
cfg.DynamicMemoryAllocation = 'AllVariableSizeArrays';