Main Content

Control Memory Allocation for Variable-Size Arrays

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:

  • You do not know the upper bound of an array.

  • You do not want to allocate memory on the stack for large arrays.

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 for variable-size arrays is enabled. To disable it, in a configuration object for fixed-point acceleration, set the EnableDynamicMemoryAllocation parameter to false.

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:

  • Disable dynamic memory allocation for smaller arrays. For smaller arrays, static memory allocation can speed up generated code. However, static memory allocation can lead to unused storage space. You can decide that the unused storage space is not a significant consideration for smaller arrays.

  • Enable dynamic memory allocation for larger arrays. For larger arrays, when you use dynamic memory allocation, you can significantly reduce storage requirements.

The default dynamic memory allocation threshold is 64 kilobytes. To change the threshold, in a configuration object for fixed-point acceleration, set the EnableDynamicMemoryAllocation to true and set a value for DynamicMemoryAllocationThreshold.

Related Topics