Hi,
In FreeRTOS, when working on large projects, how can we keep track of memory usage (stack and heap). How can we monitor how much memory is used or how much is still available?
Are there any built-in ways to detect stack overflow or memory leaks?
If the processor supports it, most FreeRTOS ports will implement “Stack Limit” registers that will trap if a task exceeds its stack size. For processors that don’t, you can enable two different stack checks, one that checks the stack pointer any time the task gets swapped out, and traps if it is out of bounds. A second one that checks if there has been a write need the end of the stack as a sign that the stack has filled. These are not perfect, and only detect the problem after the problem has occured, which is why hardware that allows direct checking and trapping has an advantage.
You can also ask FreeRTOS to examine the stack frame and determine how much space has not been used by seeing what has changed since its initialization.
Heap Usage:
The FreeRTOS provided Heap functions include the following status functions:
xPortGetFreeHeapSize: Get the amount of Heap currently available
xPortGetMinimumEverFreeHeapSize: Get the minimum amount of Heap that has ever been available
vPortGetHeapStats: Gets a number of heap statistics.
This can get you a lot of information about heap usage. Mechanically determining “leaks” is hard, as in these sorts of systems, there is often memory allocated that will never be deallocated, but hasn’t been “leaked”, as it is still in use, so finding real leaks means needing to figure out if the program ever loses track of a memory block, which is beyond the scope of FreeRTOS.
If you want to see the memory usage over time in a trace view, you may try Percepio Tracealyzer. Its offers dynamic memory analysis, plots and also periodic sampling of stack usage.