Undefined behavior & portability
10 min lesson
- Undefined behavior (UB) is any action the C standard does not define, so the compiler is free to do anything, including producing wrong results or crashing.
- Portability is the idea that a correct program should work the same on different compilers and systems; UB is the main enemy of portability.
- Think of UB as driving outside the marked lanes: the road may look fine, but the rules no longer protect you, and the result is unpredictable.
- Common causes of UB include signed integer overflow, out-of-bounds array access, using uninitialized variables, dereferencing NULL or dangling pointers, and modifying a string literal.
- The C standard specifies behavior for well-defined programs, but for UB it says nothing; compilers may assume UB never happens and optimize accordingly.
- The computer does not check for UB at runtime by default; tools like UBSan and Valgrind add checks during testing.
- The syntax to avoid UB is mostly about care: check bounds, initialize variables, cast carefully, and use unsigned for wrap-around arithmetic when needed.
- A realistic use of portability care: storing sizes in size_t, using int32_t and uint64_t from stdint.h when the width matters, and avoiding assumptions about int size.
- A surprising detail: signed integer overflow is UB in C, which is why -fwrapv changes behavior; unsigned overflow is defined as wrap-around.
- The example program shows a well-defined unsigned wrap-around and explains, in comments, why the signed version would be UB.
- Learn the common UB traps and avoid them; they are the source of most mysterious bugs.
- Never rely on signed overflow; use unsigned or wider types when wrap-around is needed.
- Use fixed-width types from stdint.h when sizes must be portable.
- Compile with -fsanitize=undefined during testing to catch UB early.
- Well-defined code is portable code. You are thinking like a pro!
#include <stdio.h>
#include <stdint.h>
int main(void) {
// Unsigned arithmetic wraps around in a well-defined way
unsigned int big = 4294967295u; // largest 32-bit unsigned
unsigned int wrapped = big + 1u;
// This prints 0 because unsigned overflow wraps
printf("wrapped: %u\n", wrapped);
// Fixed-width types make sizes explicit and portable
int32_t small = 100;
uint64_t large = 10000000000ULL;
printf("small: %d\n", small);
printf("large: %llu\n", (unsigned long long)large);
// Signed overflow would be UB; we avoid it with a check
int a = 2147483647; // INT_MAX on typical systems
if (a < 2147483647) {
a = a + 1;
}
printf("a: %d\n", a);
return 0;
}What happens: wrapped: 0 small: 100 large: 10000000000 a: 2147483647
Breaking it down
Unsigned overflow
big + 1uUnsigned arithmetic is defined to wrap around modulo 2^N, so the largest 32-bit unsigned plus 1 gives 0. This is well-defined.
Fixed-width type
int32_t small = 100;int32_t from stdint.h is exactly 32 bits on every supported platform, so its range is predictable.
64-bit value
uint64_t large = 10000000000ULL;Holds values larger than 32 bits. The ULL suffix makes the literal unsigned long long.
Avoiding signed overflow
if (a < 2147483647) a = a + 1;Checks before adding so the result stays in range. Signed overflow would be UB and the compiler could do anything.
Common undefined behaviors
| Behavior | Example | Avoid by |
|---|---|---|
| Signed overflow | INT_MAX + 1 | Check before adding |
| Out-of-bounds access | arr[10] on size 5 | Check bounds |
| Uninitialized read | int x; printf("%d", x) | Initialize variables |
| NULL dereference | *NULL | Check for NULL |
| Modifying literal | "hi"[0] = 'H' | Use a char array |
| Double free | free(p); free(p); | Free once, set NULL |
A helpful analogy
Undefined behavior is like driving outside the marked lanes. The road may look fine, and sometimes you get away with it, but the rules no longer protect you. The compiler may assume you stay inside the lanes and optimize based on that assumption, so a small mistake can turn into a big surprise.
Nesting rules
- 1.Signed integer overflow is UB; unsigned overflow is defined as wrap-around.
- 2.Never read uninitialized variables; initialize everything before use.
- 3.Do not modify string literals; copy them into a char array first if you need to change them.
- 4.Use fixed-width types from stdint.h when the exact bit width matters.
Common mistakes
Relying on signed overflow
Avoid
int x = INT_MAX + 1; // UBUse instead
if (x < INT_MAX) x++;Signed overflow is undefined. The compiler may assume it never happens and produce surprising results. Check before adding.
Modifying a string literal
Avoid
char *s = "hi";
s[0] = 'H'; // UBUse instead
char s[] = "hi";
s[0] = 'H';String literals are usually stored in read-only memory. Writing to them crashes or silently corrupts. Use a char array for mutable strings.
Assuming int is 32 bits
Avoid
int x = 3000000000; // overflow on 32-bitUse instead
int64_t x = 3000000000LL;The size of int varies. Use int64_t or long long when you need a guaranteed 64-bit value.
Quick tips
- •Compile with -fsanitize=undefined during testing to catch UB early.
- •Use stdint.h types when the exact width matters for portability.
- •Never rely on UB 'working' in your tests; it can break on a new compiler or optimization level.
- •Try compiling the example with -O2 and -fsanitize=undefined to confirm it stays clean.
- •Read the C standard's list of undefined behaviors once; it is surprisingly short and very useful.