Undefined behavior (UB) is code for which the standard imposes no requirements. Examples are signed integer overflow, out-of-bounds access, dereferencing NULL, using an uninitialized value, modifying a variable twice without a sequence point, and shifting by too many bits. The compiler may assume UB never happens, so it can delete checks, produce garbage, or "work" until the next compiler update.
Remember
int x = INT_MAX; x + 1; /* signed overflow */
int a[3]; a[3] = 0; /* out of bounds */
int *p = NULL; *p = 1; /* null dereference */
i = i++ + ++i; /* unsequenced */
Reference
Cheat Sheet
Keep these facts handy while you work with Undefined Behavior in C.
Topic
Detail
Overflow
Unsigned wraps; signed is UB
Bounds
Never exceed the object
Detect
-fsanitize=undefined,address
Avoid
Check before the operation
Code
C Examples
Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Portability.
Example 1 — Check for signed overflow before it happens
Test the operands instead of the (undefined) result.
C
#include <limits.h>
#include <stdio.h>
static int safe_add(int a, int b, int *out) {
if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) {
return 0;
}
*out = a + b;
return 1;
}
int main(void) {
int r;
if (!safe_add(INT_MAX, 1, &r)) printf("INT_MAX + 1 would overflow\n");
if (safe_add(5, 7, &r)) printf("5 + 7 = %d\n", r);
return 0;
}
Output
INT_MAX + 1 would overflow
5 + 7 = 12
How It Works
a > INT_MAX - b tests for overflow without performing the addition.
The function returns 0 and leaves the output untouched when it would overflow.
Normal additions succeed.
Edge Cases & Pitfalls
Check these before relying on Undefined Behavior in real programs.
opt
Works in debug, breaks in release
UB can behave differently with optimization. Test with sanitizers and warnings, not just by running.
assume
"It worked on my machine"
Appearing to work is allowed behavior for UB, so never rely on observed results.
Remember
Key Takeaways
UB: no guarantees at all.
Check first, operate second.
Sanitizers: use them.
One line: Undefined behavior (UB) is code for which the standard imposes no requirements.
Frequently Asked Questions
It is behavior for which the standard places no requirements, so anything can happen when a program executes such code.
Compile with -Wall -Wextra and run with -fsanitize=undefined,address (GCC or Clang), and test with Valgrind or static analyzers.
Continue with "C Portability" next. Write code that behaves the same across compilers and platforms. The C Advanced Concepts hub lists every topic in order.