What is undefined behavior in C++? Give examples.
Undefined behavior (UB) is code for which the standard gives no rules. The compiler may assume it never happens, so the result is anything: a crash, a wrong answer, or “it works on my machine”.
- Reading a variable which is not initialized.
- An array index out of range, or dereferencing
nullptr. - Signed integer overflow (unsigned overflow is defined: it wraps).
- Using an object after it is deleted (dangling pointer).
- Two threads changing the same data without a lock (data race).
- Modifying a
constobject, or a missing return in a function which returns a value.
Tools find UB while testing. We compile this code with the undefined behavior sanitizer:
#include <climits>
#include <iostream>
int main() {
int x = INT_MAX;
x = x + 1; // signed overflow: undefined behavior
std::cout << x << '\n';
}
Terminal
$ g++ -std=c++23 -fsanitize=undefined ub.cpp -o ub
$ ./ub 2>&1 | sed 's/^[^ ]*ub.cpp/ub.cpp/'
ub.cpp:6:7: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
-2147483648
Use -fsanitize=address,undefined and -Wall -Wextra in every test build.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |