This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

clib malloc/free calls interrupt safety

Hi. I have a question if is it safe to call malloc/free function of clib from the handler of ble events of softdevice.
Does anybody know if is it safe?
Does Nordic have some memory allocator which is interrupt safe?

  • So malloc/free are not interrupt safe, which is why the general rule is never to call them from an interrupt. There exist interrupt safe versions but neither the libc one nor any of the other implementations in the SDK are. 

    However. If you are only calling malloc/free from the ble event handler, you're ok, because that handler is driven from an interrupt, but just one, so you are guaranteed never to end up with nested mallocs. That is only true however if the ble handler is the *only* place you call malloc/free from, no calling it from the main context or any other interrupt(*). If you can guarantee that, you're fine using the libc malloc/free. 

    If you need more than that, you'll have to write your own interrupt-safe malloc or use different pools of memory for different interrupts

    (*) technically you could call it from any interrupt with the same priority as the one which drives the ble event handler but it's better just to say, only call it from the event handler and nowhere else. 

Related