</>EmbeddedInterview

What is a reentrant function?

MediumEmbedded C

Short answer: A function is reentrant if it can be interrupted partway through and safely called again (from an ISR, a signal handler or recursion) before the first call has finished, with both calls producing correct results. That requires using only its arguments and local variables, or protecting any shared state, and calling only other reentrant functions.

Requirements

  • No modification of static or global data without protection.
  • No returning pointers to static internal buffers.
  • No calls to non-reentrant functions (malloc, printf, strtok, rand, asctime, most stdio).
  • No self-modifying code, and hardware accessed in a way that tolerates interleaving.

Non-reentrant vs reentrant

/* NOT reentrant: shared static buffer */
char *to_hex(uint8_t v)
{
    static char buf[3];
    buf[0] = "0123456789ABCDEF"[v >> 4];
    buf[1] = "0123456789ABCDEF"[v & 0xF];
    buf[2] = '\0';
    return buf;                 /* a second call (from an ISR) overwrites the first result */
}

/* reentrant: the caller provides the storage */
char *to_hex_r(uint8_t v, char out[3])
{
    out[0] = "0123456789ABCDEF"[v >> 4];
    out[1] = "0123456789ABCDEF"[v & 0xF];
    out[2] = '\0';
    return out;
}

Standard library examples: strtok → strtok_r, rand → rand_r, localtime → localtime_r, gmtime → gmtime_r. In newlib, reentrancy is handled with a per-thread struct _reent; RTOSes like FreeRTOS can switch it per task (configUSE_NEWLIB_REENTRANT).

Why it matters in embedded systems: any function called from both an ISR and the main loop (a logging function, a CRC routine, a driver helper) must be reentrant, otherwise the ISR can corrupt the main loop's work in progress, causing rare, timing-dependent bugs.

Note: reentrant is not the same as thread-safe (next question).