Topics / Debugging, Testing & Tools / Q6
Why can printf debugging change program behaviour?
Short answer: printf is slow (formatting plus a blocking UART at 115200 baud takes about 87 µs per character, so a 40-character line costs ~3.5 ms), uses a lot of stack (often 0.5–1 KB or more with floating-point formatting), may allocate memory or take locks, and is usually not safe to call from interrupts. Adding it changes timing, stack usage and memory layout, so race conditions and timing bugs may disappear or new ones may appear (a "Heisenbug").
Better ways to get information out
| Technique | Cost | Notes |
|---|---|---|
| GPIO toggle + scope/logic analyser | ~10 ns | best for timing, ISR entry/exit, latency |
| RAM trace buffer (event ID + timestamp + value) | a few cycles | dump later with the debugger or over a link |
| SEGGER RTT | ~1 µs per message, no blocking | writes to a RAM ring buffer read by the J-Link while running |
ITM/SWO (ITM_SendChar) |
fast, single-wire | requires an SWO pin and probe support |
| Deferred logging (log IDs + arguments, formatted on the host) | very low | e.g. Trice, defmt (Rust), Zephyr dictionary logging |
| Asynchronous log task with a queue | moderate | formatting happens later, at low priority |
If you must use printf
- Use a non-blocking, buffered implementation with DMA, and never call it from ISRs.
- Retarget
_write(newlib) to your UART or RTT; use newlib-nano and avoid%f(or enable-u _printf_floatonly if needed). - Remember that disabling printf in release builds also changes timing — test the release configuration.