Undefined Behavior & Writing Safer C
Prerequisites: Memory management in depth
Undefined behavior means the C standard places no requirement
at all on what happens — the compiler is free to do anything,
including something that looks like it "works" on one machine and
crashes (or worse, silently corrupts data) on another. Several
examples from earlier lessons are all undefined behavior: reading
an uninitialized variable, indexing an array out of bounds,
dereferencing a dangling or NULL pointer, and signed integer
overflow.
Modern practice for writing safer C:
- Always initialize variables, even to an obviously "unused" default.
- Compile with
-Wall -Wextra -fsanitize=address,undefinedduring development — the sanitizers catch a large fraction of these bugs immediately, with a clear error message, instead of a confusing crash (or no crash at all) later. - Prefer the "n" or bounds-aware standard library functions
(
strncpy,snprintf) covered in Level 2.
Common mistakes
- Treating "it ran fine on my machine" as proof a piece of code is correct — undefined behavior is, by definition, not guaranteed to behave the same way twice.