Collecting heap usage statistics
Technical Note 28545
9/20/2023 12:14 PM
This Technical Note describes how to collect heap usage statistics in an application.
With IAR Embedded Workbench for ARM version 6.60 and later, you can collect heap usage statistic. That is, becoming able to track the amount of memory used by malloc and similar functions
Enabling the feature
In the application add the function call:
To get a simple printout on
stderr, call the function:
Where the output from
__iar_dlmalloc_stats() looks like (for example):
max system bytes = 2048
system bytes = 2048
in use bytes = 16
The functions above are declared and defined in the files
To be able to call these functions, use the header file
mallocstats.h that you can download here. (The zip file also contains an example file
main_test.c that shows how to use the function calls.)
About maximum heap usage
The following text is from the article Mastering stack and heap for system reliability, under the heading How to set the heap size.
"For systems that mimic desktop systems by emulating sbrk(), the maximum heap usage will be given by malloc_max_footprint(). For embedded systems that do not emulate sbrk(), it is common to give the entire heap to the memory allocator in one chunk. In that case malloc_max_footprint() becomes worthless; it will simply return the size of the entire heap."
In the article there are some tips and tricks on how to calculate how much heap is used.
Note: The IAR Embedded Workbench does not emulate
Handling different versions of EWARM
In IAR Embedded Workbench for ARM versions 9.30, 9.32 and 9.40 you must enable the 'Advanced Heap' as these functions are part of that implementation.
Do this at: Project > Options > General Options > Library Options 2 > Heap Selection > Advanced Heap
For IAR Embedded Workbench for ARM versions earlier than 8.10, the files
dlmalloc_stat.c are located in the
For IAR Embedded Workbench for ARM versions earlier than version 6.60, you must include the file
arm\src\lib\dlmalloc.c in your project, and set the defines
NO_MALLOC_STATS to 0. Note that you must copy the dlmalloc.c file to the project directory and modify it there. Also note that in a C++ project, the
dlmalloc.c file must be compiled as a C file.
The heap usage can be measured. The heap is described in the IAR C/C++ Development Guide for ARM, under chapter Dynamic memory on the heap.
All product names are trademarks or registered trademarks of their respective owners.