Undefined Behavior & Safety

'it works on my machine' is not correctness

There is a phrase every programmer says and every programmer eventually regrets: 'but it works on my machine'. Its cousin is 'but it compiled' and 'there were no warnings'. Each of these feels like proof that the code is correct. None of them is. Understanding WHY is one of the most maturing realizations in learning C, because in C the gap between 'seems to work' and 'is correct' is wide enough to drive a security breach through.

Here is the crux. 'It compiled' only means the code was grammatically valid C that the compiler could translate — it says nothing about whether the program does the right thing, or even whether it stays within defined behavior. 'No warnings' is better but still weak: warnings catch some mistakes, but the compiler is not required to diagnose undefined behavior, and the most dangerous bugs produce no warning at all. And 'it works on my machine' is the most treacherous, because undefined behavior often APPEARS to work. A program that reads an uninitialized variable, overflows a buffer by a few bytes, or relies on signed overflow may run flawlessly on your computer, with your compiler, at your optimization level, on your inputs — and then break on a teammate's machine, in a release build, on a different CPU, or simply on an input you never tried. The behavior was never guaranteed; you were just getting lucky, and luck is not a property you can ship.

Why this matters: this is the practical reason undefined behavior is so insidious and why the rest of this field exists. The defenses are about replacing luck with evidence: turn on warnings and treat them as errors (gcc -Wall -Wextra -Werror); run sanitizers (AddressSanitizer, UBSan) that actively detect undefined behavior at runtime; test on more than one compiler and optimization level; write tests that exercise the boundary inputs, not just the happy path; and reason about your code against the standard's rules rather than against what your machine happened to do today. 'It works on my machine' is the beginning of an investigation, never the end of one.

/* 'works' at -O0, breaks at -O2: undefined behavior is hiding */ int x; /* uninitialized */ if (x == 0) /* reads garbage: UB */ launch(); /* evidence over luck: */ $ gcc -O2 -Wall -Wextra -Werror -fsanitize=address,undefined main.c $ ./a.out /* sanitizers report the UB at runtime */

The same code can pass on your machine and fail elsewhere. Warnings-as-errors plus sanitizers turn silent UB into a loud, reproducible report.

A clean compile and a successful run prove only that nothing happened to surface the bug this time. Undefined behavior can stay invisible for years and then break on a new compiler, a new input, or a higher optimization level.

Also called
it compiledworks on my machine在我機器上能跑它編譯過了