Main Content

Stack Allocation and Performance

By default, local variables are allocated on the stack. Large variables that do not fit on the stack are statically allocated in memory.

Stack allocation typically uses memory more efficiently than static allocation. However, stack space is sometimes limited, typically in embedded processors. MATLAB® Coder™ allows you to manually set a limit on the stack space usage to make your generated code suitable for your target hardware. You can choose this limit based on the target hardware configurations. For more information, see Control Stack Space Usage.

For limited stack space, you can choose to allocate large variables on the heap instead of using static allocation. Heap allocation is slower but more memory-efficient than static allocation. To allocate large variables on the heap, do one of the following:

Allocate Heap Space from Command Line

  1. Create a configuration object. Set the property, MultiInstanceCode, to true.

    cfg = coder.config('exe');
    cfg.MultiInstanceCode = true;

  2. Generate code using this configuration object.

Allocate Heap Space Using the MATLAB Coder App

  1. Using the MATLAB Coder app, in the project settings dialog box, on the Memory tab, select the Generate re-entrant code check box.

  • Generate code.

See Also