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

Main Content

Dynamic memory allocation allocates memory on the heap as needed at run-time, instead of allocating memory statically on the stack. Dynamic memory allocation is beneficial when:

Dynamic memory allocation and the freeing of this memory can result in slower execution of the generated code. To control the use of dynamic memory allocation for variable-size arrays, you can:

Provide Upper Bounds for Variable-Size Arrays

For an unbounded variable-size array, the code generator allocates memory dynamically on the heap. For a variable-size array with upper bound, whose size, in bytes, is less than the dynamic memory allocation threshold, the code generator allocates memory statically on the stack. To prevent dynamic memory allocation:

  1. Specify upper bounds for a variable-size array. See Specify Upper Bounds for Variable-Size Arrays.
  2. Make sure that the size of the array, in bytes, is less than the dynamic memory allocation threshold. See Configure Code Generator to Use Dynamic Memory Allocation for Arrays Bigger Than a Threshold.

Disable Dynamic Memory Allocation

By default, dynamic memory allocation is enabled for variable-size arrays. To disable it:

If you disable dynamic memory allocation, you must provide upper bounds for variable-size arrays.

Configure Code Generator to Use Dynamic Memory Allocation for Arrays Bigger Than a Threshold

Instead of disabling dynamic memory allocation for all variable-size arrays, you can specify for which size arrays the code generator uses dynamic memory allocation.

Use the dynamic memory allocation threshold to:

The default dynamic memory allocation threshold is 64 kilobytes. To change the threshold: