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:
errno is always ENOMEM after the malloc() callHow can I resolve this issue?
When you look at the definition of _sbrk in os/various/syscalls.c, you can clearly see that it always returns a ENOMEM error if CH_CFG_USE_MEMCORE == FALSE.
Unless you set CH_CFG_USE_MEMCORE = TRUE in chconf.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:
#define CH_CFG_USE_MEMCORE TRUE
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).