mbed rtos & malloc in ISR causes crash

25 Mar 2012

The combination of the below conditions causes a runtime crash:

a) the project *contains* the rtos library (it does not have to use it/link to it)
b) calling "new" / "malloc" or growing a std lib container inside an ISR (in my case called by an InterruptIn)

This effectively prevents allocating any memory inside an ISR when using this rtos library, which breaks other libraries which rely on dynamic data structures.

Sample program: http://mbed.org/users/narshu/programs/radiotest2/m7gs7d
rtos library: http://mbed.org/handbook/RTOS

26 Mar 2012

Never prudent to do library calls, let alone malloc() ( related to C++ "new" ), from an ISR. Cardinal rule of an ISR: Get in, get out. Pronto. No loops, few or now function calls and no library calls for reentrancy reasons.

You might get away breaking these rules, if you use a certain set of constraints, and, likely, have a Linux-class OS.

26 Mar 2012

Oskar Weigl wrote:

the below conditions causes a runtime crash [...] calling "new" / "malloc" or growing a std lib container inside an ISR

malloc is not re-entrant. malloc is made thread safe using mutexes.

You cannot use mutexes in ISR, therefore you cannot use malloc in ISR.

new is calling malloc, therefore you cannot use new in ISR.

As Steve pointed out, it is anyway good practice to make the ISR as fast as possible avoiding library calls.

A typical use case for an ISR is copying a small buffer from/to a peripheral and then setting a flag to wake up the correspondent RTOS thread interested in this buffer.

In your case, an InterruptIn ISR should probably simply signal a waiting thread and exit. If you have multiple InterruptIn, instead of a signal, you could push messages in a queue.

If you want to read more documentation about this separation of responsibilities, this is how other Operating Systems are naming it:

  • Linux: Top Half / Bottom Half
  • eCos: Interrupt Service Routine / Deferred Service Routine

I will update the RTOS documentation to make it clear that you cannot use malloc and new in ISR.

Cheers, Emilio