How to avoid undefined behavior
Know common causes
Undefined behavior includes out-of-bounds access, use-after-free, null dereference, signed overflow, invalid shifts, and mismatched variadic format arguments.
- Initialize objects before reading them
- Keep indexes and pointer arithmetic within bounds
- Match every
printf/scanfspecifier to its argument - Never use memory after its lifetime ends
Understand the consequence
Undefined behavior is not a predictable error value. A program may appear to work, crash, leak data, or change behavior under optimization or on another compiler.
Turn on diagnostics
Warnings catch suspicious source patterns; sanitizers add runtime checks during testing. They improve detection but cannot prove a program safe.
cc -std=c17 -Wall -Wextra -Wpedantic -Wconversion -g \
-fsanitize=address,undefined program.c -o program
./program
Design for safety
Track buffer capacities, validate indexes and arithmetic before use, check library return values, and make ownership and lifetimes explicit. Test boundary cases such as empty input and maximum lengths.