ARMCLANG: Using the Heap and Stack
Information in this knowledgebase article applies to:
I am developing an application, but I am not sure how much heap and stack to allocate.
Is there a general overview to setup the stack and heap? How does the stack and heap work? How can I measure the memory usage?
Location to specify heap size and main stack size: Often, an MDK project will use a startup assembly file, ending with "*.s", to specify both the heap and the main stack size. Exception handlers use the main stack. The main stack pointer (MSP) is used after reset, so by default, the language library startup will also use the main stack.
The stack and heap size could also be defined using macros, elsewhere in the project. Alternatively, the stack and heap may be defined in a scatter file or in a C/C++ source file. A library project does not even require a stack or heap definition. Use "Ctrl+F" to perform a project-wide search, if you are still unsure of the location.
Explanation of a stack: A great explanation of the main stack for a Cortex-M v6-M or v7-M device is a blog written by Joseph Yiu, "How much stack memory do I need for my Arm Cortex-M applications?". It also discusses the limitations of measuring the main stack. This article mentions a static callgraph approach. For more information, see "Stack use in C and C++", below.
RTX threads: Configure the size of the stack for CMSIS RTOS RTX threads (MSP or PSP (Process Stack Pointer) The blog described above also shows a table to look at the stack usage by each thread, the System and Thread Viewer.
RTX5 threads: Configure the size of the stack for CMSIS RTOS2 RTX5 threads (MSP or PSP): The stack usage percentage is displayed in the "RTX RTOS" Component Viewer dialog, under Threads => id: x => Stack. ARM: RTX5 awareness in µVision debugger when using ARMCC is supported in MDKv5.25 or later.
Heap Implementation and Usage: A good description of the heap implementation can be found in our guide: Choosing a heap implementation for memory allocation functions.
A heap is not necessary for every Cortex-M application. The requirement of the application is probably dynamic memory allocation, so there are alternatives. A RTOS may provide more feature-rich dynamic memory allocation, than a C library's heap implementation. Using the function malloc from the C library is portable. The CMSIS RTOS2 standard is designed to combine portability with additional features, like object specific memory pools to dynamic memory allocation to avoid fragmentation.
For detailed heap usage information, you can use __heapstats().
Last Reviewed: Wednesday, June 13, 2018
of your data.