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.

Bottom lineA 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

An off-by-one bug, and its fixC: edit and run

Change the condition to i <= 5 to see how an off-by-one error reads one element past the end of the array.

PitfallFix
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 itAlways 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 writesMark 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
Tip:This checklist is worth memorizing before the register/interrupt lessons later in this course — nearly every pitfall listed here becomes more dangerous once real hardware is involved.

Try it: why a narrow accumulator needs a wider type

Simulating what a narrow accumulator would show after overflowC: edit and run

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?