Home / Learn Embedded C / Common C Pitfalls in Embedded Code
Common C Pitfalls in Embedded Code
A checklist of the mistakes that cause the most real-world embedded bugs.
Breaking it down
Definition
Most embedded bugs trace back to a short list of well-known C pitfalls: off-by-one array access, uninitialized variables, integer overflow, and forgetting volatile on hardware/interrupt-shared data.
Why you need this
Knowing this checklist in advance means recognizing these bug patterns instantly during code review, instead of spending hours debugging them on real hardware later.
How it works
Each pitfall has a simple, repeatable fix: bound-check array access, always initialize variables, choose wide-enough types for sums, and mark hardware/ISR-shared variables volatile (covered in the Memory group).
Where you'll see this
- Code review
- Debugging checklists
- Interview preparation
Try it
Change the condition to i <= 5 to see how an off-by-one error reads one element past the end of the array.
| Pitfall | Fix |
|---|---|
| Off-by-one array access (arr[len] instead of arr[len-1]) | Always loop with i < len, never i <= len |
| Using a variable before initializing it | Always give local variables an initial value |
| Integer overflow (e.g. summing many 16-bit values into a 16-bit total) | Use a wider accumulator type (e.g. int32_t) for sums |
| Forgetting volatile on a variable an ISR writes | Mark any variable shared with an ISR as volatile (Memory group) |
| Comparing with = instead of == | Watch compiler warnings; some teams write "5 == x" to force an error on a typo |
Try it: why a narrow accumulator needs a wider type
Summing three large 16-bit-ish values overflows a 16-bit accumulator; the modulo here shows what a real narrow accumulator would display, without actually overflowing a variable (unsupported by this sandbox).
Test what you just read
1. What is a simple, repeatable fix for integer overflow when summing many values?
A wider type (like int32_t for a sum of many int16_t values) gives the total room to grow without wrapping around.