Try Embedded

Integer traps on an 8-bit chip

Six short C bugs that the Uno makes visible because its int is 16 bits, each next to its fix, with the MISRA rule or compiler warning that would have caught it.

Firmware · Intermediate

In a real product: Code review checklist for a meter (Energy): Firmware teams check every calculation against these traps before an energy meter is certified.

On a PC, int is 32 bits and most overflow bugs stay hidden. On the Uno's ATmega328P, int is 16 bits: from −32768 to 32767. The same bugs show up with everyday numbers. This sketch runs six traps, each next to its fixed version, and prints both results.

Some of them are plain wrong arithmetic. Others are undefined behaviour: the C standard says nothing about the result, so the compiler may do anything, including what looks right today.

What you'll learn

  • Why 60 * 1000 doesn't fit in a 16-bit int, and why 60000UL or a cast fixes it
  • Integer promotion: what uint8_t + uint8_t becomes, and when a uint16_t comparison turns signed
  • Comparing a signed value with an unsigned one (-1 < sizeof x is false)
  • 1 << 15 and 1 << 16 on a 16-bit int, and why 1UL << n is the habit to have
  • The timer-wrap bug: if (millis() > deadline) against if (millis() - start >= wait)
  • Which MISRA C rules and compiler warnings (-Wconversion, -Wsign-compare) catch each trap

How it works

  1. Overflow in a constant expression. int ms = 60 * 1000; computes 60000 in int, which is too big. The compiler warns, the result wraps to −5536. Writing 60 * 1000UL makes the sum unsigned long.
  2. Signed overflow at run time. a * b with two ints of 300 and 200 is undefined behaviour. GCC happens to wrap it, so it prints −5536. Casting one side to long first does the sum in 32 bits.
  3. Signed against unsigned. -1 < sizeof(buffer) compares an int with a size_t. The -1 turns into 65535, so the test is false. Cast the size to int, or keep both signed. (MISRA C:2012 rule 10.4.)
  4. Shifting into the sign bit. 1 << 15 in a 16-bit int sets the sign bit, and 1 << 16 is undefined. A mask for bit 20 must be 1UL << 20. (Rule 12.2: shift by less than the width.)
  5. Truncation. Storing analogRead() * 4 in a uint8_t keeps only the low 8 bits. -Wconversion warns about it.
  6. Timer wrap. A 16-bit timestamp counter wraps after 65535 ms. now > deadline fails right after the wrap, but (uint16_t)(now - start) >= wait stays correct, because unsigned subtraction wraps too. The sketch uses a 16-bit counter so the wrap happens at once instead of after millis()'s 49 days.

The values come from volatile variables, so the compiler can't work the results out in advance and hide the bugs.

Try this

  • Change trap 2's numbers to 100 and 300: still wrong? Find the largest pair that fits.
  • Turn trap 6's counter into uint32_t and explain why the wrong version now seems to work.
  • In your own sketches, turn on "All" compiler warnings and look for -Wsign-compare and -Woverflow messages.

sketch.ino

// Six integer traps on the Uno's 16-bit int, each with its fix. Values come through volatile variables, so the
// compiler can't work them out in advance.
volatile int a = 300, b = 200;
volatile int minusOne = -1;
volatile int reading = 1000;
volatile uint8_t shift = 15;
char buffer[10];

void show(const __FlashStringHelper *what, long wrong, long right) {
  Serial.print(what);
  Serial.print(F("  wrong: "));
  Serial.print(wrong);
  Serial.print(F("  right: "));
  Serial.println(right);
}

void setup() {
  Serial.begin(9600);
  Serial.print(F("sizeof(int) = "));
  Serial.println(sizeof(int));

  // 1. A constant expression too big for int (the compiler warns: -Woverflow).
  long wrong1 = 60 * 1000;
  long right1 = 60 * 1000UL;
  show(F("1. 60 * 1000          "), wrong1, right1);

  // 2. Signed overflow at run time: undefined behaviour (MISRA C:2012 rule 12.4's intent; -ftrapv would trap).
  long wrong2 = a * b;
  long right2 = (long)a * b;
  show(F("2. 300 * 200          "), wrong2, right2);

  // 3. Signed against unsigned: -1 becomes 65535 (rule 10.4; -Wsign-compare).
  show(F("3. -1 < sizeof buffer "), minusOne < sizeof buffer, minusOne < (int)sizeof buffer);

  // 4. Shifting into the sign bit of a 16-bit int (rule 12.2).
  long wrong4 = 1 << shift;
  long right4 = 1UL << shift;
  show(F("4. 1 << 15            "), wrong4, right4);

  // 5. Truncation into a uint8_t (-Wconversion).
  uint8_t wrong5 = reading * 4;
  uint16_t right5 = reading * 4;
  show(F("5. 1000 * 4 in a byte "), wrong5, right5);

  // 6. Timer wrap: a 16-bit timestamp counter that wraps after 65535.
  uint16_t start = 65000, wait = 1000;
  uint16_t deadline = start + wait;         // 464: wrapped past 0
  uint16_t now = 65100;                     // only 100 ms later
  show(F("6. time up after 100? "), now > deadline, (uint16_t)(now - start) >= wait);
}

void loop() {}

Lessons behind it