Undefined Behavior
Undefined Behavior is behavior for which the C/C++ standard imposes no requirements.
In other words, the program can crash, continue or have different behaviors on different platforms.
Here is an example of a UB:
#include <iostream>
int main() {
int a;
// UB in C and pre-C++26: uninitialized memory access
if (a >= 0) {
std::cout << "non negative" << std::endl;
} else {
std::cout << "negative" << std::endl;
}
return 0;
}Uninitialized memory has what is called indeterminate values, values which are unspecified. The actual value of a depends on the platform and the compiler.
Why it Matters?
Compilers are not required to give warnings or errors for undefined behaviors and having them in your code can lead to non-portable behaviors, strange bugs and security vulnerabilities.
Common UBs
Signed integer overflow
cppint x = INT_MAX; // UB int y = x + 1;INFO
Unsigned integer overflow is defined.
UINT_MAX + 1 == 0is true.Out-of-bound access
cppint a[5] = {1,2,3,4,5}; // UB int x = a[5];Uninitialized memory access
cppint x; // UB pre-C++26 int y = x;INFO
Since C++26: this is classified as erroneous behavior, not undefined behavior.
