I have a ChibiOS application where I'm using dynamic memory allocation via malloc()
.
However, I observed that 100% of the time I call malloc()
, it returns NULL
. I have confirmed that:
- The microcontroller memory is not full
- The error also occurs for size-1 malloc calls, so the memory chunk size is not the cause of the issues.
errno
is alwaysENOMEM
after themalloc()
call
How can I resolve this issue?
When you look at the definition of
_sbrk
inos/various/syscalls.c
, you can clearly see that it always returns aENOMEM
error ifCH_CFG_USE_MEMCORE == FALSE
.Unless you set
CH_CFG_USE_MEMCORE = TRUE
inchconf.h
, the ChibiOS core memory manager is disabled completely and_sbrk
and other memory-related functions are only included in the object files so no linking errors occur.In order to properly configure ChibiOS correctly, ensure that the following is set in
chconf.h
:In order to avoid running into reliability issues, you might want to use memory pools or alternative algorithms instead where possible. See this detailed explanation for a description why
malloc()
is often a bad idea on embedded systems (it's actually forbidden in most embedded coding standards entirely).