malloc() always returns NULL in ChibiOS

736 views Asked by At

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 always ENOMEM after the malloc() call

How can I resolve this issue?

1

There are 1 answers

0
Uli Köhler On BEST ANSWER

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).