Control Dynamic Memory Allocation for Fixed-Size Arrays - MATLAB & Simulink (original) (raw)

Main Content

The code generated by MATLAB® Coder™ allocates memory to the program stack for fixed-size arrays whose size is less than a specified threshold. For example, in the following code,Z is a fixed-size 1-by-4 array.

function Z = myfcn() Z = zeros(1,4); end

Dynamic memory allocation allocates memory on the heap, instead of the program stack. Consider dynamic memory allocation for large fixed-size arrays that might exhaust stack memory.

Dynamic memory allocation might result in slower execution of the generated code.

Enable Dynamic Memory Allocation for Fixed-Size Arrays

By default, dynamic memory allocation for fixed-size arrays is disabled. Use one of these methods to enable it.

Set Dynamic Memory Allocation Threshold for Fixed-Size Arrays

When dynamic memory allocation for fixed-size arrays is enabled, the code generator allocates memory dynamically on the heap for fixed-size arrays whose size (in bytes) is greater than or equal to the dynamic memory allocation threshold.

The default dynamic memory allocation threshold is 64 kilobytes. To configure the threshold, use one of these:

Generate Code for Fixed-Size Arrays

Define a MATLAB function that calculates the product of two large fixed-size arrays a andb.

function y = productLargeSize(a,b) y = a*b; end

Generate C code.

cfg = coder.config('lib'); cfg.VerificationMode="SIL"; cfg.DynamicMemoryAllocationForFixedSizeArrays = true; t = coder.typeof(0,[1e4 1e4]); codegen productLargeSize -args {t,t} -config cfg - report

By enabling dynamic memory allocation for fixed-size arrays, arraysa and b is dynamically allocated on the heap, preventing stack overflow.

Generated Code

... void tlargeSize(const emxArray_real_T *a, const emxArray_real_T *b, emxArray_real_T *y) { const double *a_data; const double *b_data; double *y_data; ...

Usage Notes and Limitations

When dynamic memory allocation for fixed-size arrays is enabled:

Note

Enabling dynamic memory allocation for fixed-size arrays is not supported for GPU code generation.

See Also

coder.EmbeddedCodeConfig | coder.MexCodeConfig | coder.CodeConfig