What Is Undefined Behavior (UB) and Why Is It Dangerous?
In languages like Python or Java, a program either works or throws an error. In C and C++, things are different. Here we have UB — undefined behavior. This is a situation where the language standard does not say what the program should do. And then the compiler can do anything.
What is UB
Undefined behavior is code that is formally allowed for the compiler, but the result is unpredictable. The C standard does not describe what will happen — and the compiler is not required to warn you.
Examples of UB:
Out-of-bounds array access
Division by zero
Dereferencing a NULL pointer
Using an uninitialized variable
Signed integer overflow
Modifying a variable twice in one expression (i = i++)
Why it's dangerous
Unpredictability — the program may work today and break tomorrow
Optimizations — the compiler uses UB to speed up code and breaks logic
Security — UB is a common cause of vulnerabilities
Debugging — UB is hard to find, because the bug doesn't always show up
Example
c
int arr[3];
arr[5] = 10; // out-of-bounds — UB
This may:
work and break nothing
corrupt a neighboring variable
cause a segmentation fault
do literally anything
Why the compiler doesn't save you
The compiler optimizes code assuming that UB does not exist. If UB is present, the optimization can break the logic:
c
int x = 0;
if (x + 1 > x) { ... } // the compiler may remove this check
Because signed integer overflow is UB. So the compiler is allowed to assume it won't happen.
How to avoid UB
Read the standard — know what is allowed
Enable warnings — -Wall -Wextra in GCC
Use sanitizers — -fsanitize=undefined,address
Write carefully — check bounds, pointers, initialization
Use Rust — UB is almost impossible there
Conclusion
UB is not a bug. It's a hole in the standard.
The compiler is not required to catch it.
A program may work for years — and break at the worst possible moment.
Understanding UB is what separates a beginner from a systems programmer.
If you know where your code can become unpredictable, you write reliable code.