Current best dynamic memory allocation method

I want to use dynamic memory allocation.  After searching these forums, I see the following options:

  • malloc
  • k_malloc
  • nrf_malloc
  • balloc

I haven't had success with getting any of them to work.  I've found numerous references to modifying sdk_config.h, which is not a file I have in my project.  (All my configurations are going through proj.conf).

What is the current best way to get some version of malloc/free working?  Where and how do I define my heap size?  Currently I'm getting linker errors for undefined references to nrf_mem_init, nrf_malloc, etc.  I've defined CONFIG_HEAP_MEM_POOL_SIZE=8192 in my proj.conf but it doesn't make a difference.

  • After a lot of trial and error I've made some progress.  I needed to define the stack space as well as the heap in order for it to work with k_malloc.  Here is the relevant portion of my current prj.conf:

    CONFIG_HEAP_MEM_POOL_SIZE=2048
    CONFIG_MAIN_STACK_SIZE=16384

    Without that stack definition the code seems to just endlessly get stuck in the startup code before it ever branches to main.

    But, I can't increase my heap size beyond 2048 or it goes back to failing in the same way as before.  This seems similar to this issue.  This is certainly not right:  I'm compiling a test application, and even with that 16k stack and 2k heap I'm only using a tiny portion of the available ram:

    Memory region         Used Size  Region Size  %age Used

               FLASH:       24460 B         1 MB      2.33%

                SRAM:       20896 B       256 KB      7.97%

    Can someone help me increase that heap size to more than 2k...?  And confirm for me if k_malloc is the recommended way of doing dynamic allocation with a zephyr based project built with 1.7.1?

  • Hello,

    I've found numerous references to modifying sdk_config.h, which is not a file I have in my project.

    This is for when you are building with the nRF5 SDK, not with Zephyr/NCS.

    BDA said:
    Without that stack definition the code seems to just endlessly get stuck in the startup code before it ever branches to main.

    Can you set CONFIG_RESET_ON_FATAL_ERROR=n and post the serial output log here so I can see what is going wrong? It would be nice if you could share the code as well, or the part of the code that fails.

Related