Undefined behavior: signed overflow in C
Signed overflow is undefined, so the compiler may assume it never happens.
#include <limits.h>
/* The compiler may assume a + 1 > a always holds. */
int broken_check(int a) {
return a + 1 > a;
}
/* Correct: ask before the arithmetic happens. */
int safe_check(int a) {
return a < INT_MAX;
}
unsigned int wraps_defined(unsigned int a) {
return a + 1u;
}
How it works
- Unsigned arithmetic wraps and is well defined.
- Signed overflow lets the optimizer delete your check.
- So test before the addition, never after it.
Keywords and builtins used here
broken_checkintreturnsafe_checkunsignedwraps_defined
The run, in numbers
- Lines
- 15
- Characters to type
- 280
- Tokens
- 48
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 27 seconds.
Step 1 of 3 in Undefined behavior, step 8 of 13 in Unions, bitfields & undefined behavior.