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 * 1000doesn't fit in a 16-bitint, and why60000ULor a cast fixes it - Integer promotion: what
uint8_t + uint8_tbecomes, and when auint16_tcomparison turns signed - Comparing a signed value with an unsigned one (
-1 < sizeof xis false) 1 << 15and1 << 16on a 16-bitint, and why1UL << nis the habit to have- The timer-wrap bug:
if (millis() > deadline)againstif (millis() - start >= wait) - Which MISRA C rules and compiler warnings (
-Wconversion,-Wsign-compare) catch each trap
How it works
- Overflow in a constant expression.
int ms = 60 * 1000;computes 60000 inint, which is too big. The compiler warns, the result wraps to −5536. Writing60 * 1000ULmakes the sumunsigned long. - Signed overflow at run time.
a * bwith twoints of 300 and 200 is undefined behaviour. GCC happens to wrap it, so it prints −5536. Casting one side tolongfirst does the sum in 32 bits. - Signed against unsigned.
-1 < sizeof(buffer)compares anintwith asize_t. The-1turns into 65535, so the test is false. Cast the size toint, or keep both signed. (MISRA C:2012 rule 10.4.) - Shifting into the sign bit.
1 << 15in a 16-bitintsets the sign bit, and1 << 16is undefined. A mask for bit 20 must be1UL << 20. (Rule 12.2: shift by less than the width.) - Truncation. Storing
analogRead() * 4in auint8_tkeeps only the low 8 bits.-Wconversionwarns about it. - Timer wrap. A 16-bit timestamp counter wraps after 65535 ms.
now > deadlinefails right after the wrap, but(uint16_t)(now - start) >= waitstays correct, because unsigned subtraction wraps too. The sketch uses a 16-bit counter so the wrap happens at once instead of aftermillis()'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_tand explain why the wrong version now seems to work. - In your own sketches, turn on "All" compiler warnings and look for
-Wsign-compareand-Woverflowmessages.
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() {}