Debugging & Toolchain · Interview question

Why shouldn't you call printf in an interrupt handler or hot loop?

A strong answer

Several reasons, all about cost and safety. First, printf is expensive: formatting the string takes many cycles, and the transport, especially a blocking UART that sends bytes at the baud rate, can take far longer than the code you're observing, so a printf inside a 1 kHz ISR can easily exceed the interrupt period, causing missed deadlines, dropped data, and a system that spends all its time printing; it can even keep the core blocked long enough to trip the watchdog. Second, printf (and the underlying buffered I/O) is generally not reentrant, it uses shared internal state and buffers, so calling it from both a task and an ISR (or concurrently from two tasks without locking) can corrupt that state and produce garbled or crashed output. Third, it perturbs timing, so the very real-time bug you're trying to observe may shift or vanish (a Heisenbug) when you add the print. The correct approach for logging from hot paths is deferred logging: the call in the ISR/hot path does the minimum, enqueue a small record or copy a few bytes into a ring buffer (cheap, non-blocking), and a low-priority task or the idle hook later drains the buffer to the slow transport, so the critical path pays almost nothing and the expensive formatting/I/O happens off the deadline path. So you keep printf-style logging out of ISRs and tight loops, and use a deferred, non-blocking logging mechanism there instead.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

printf Debugging & Logging

Where does printf go on a chip with no console, and what does it cost? Retargeting output to UART/SWO/RTT (vs slow halting semihosting), intrusiveness, and leveled, deferred, compile-gated logging.

More printf Debugging & Logging questions

Browse all 472 interview questions
Why shouldn't you call printf in an interrupt handler or hot loop? | EmbeddedPrep.io