# C++ Undefined behavior **[Undefined behavior](https://en.cppreference.com/w/cpp/language/ub)** occurs when a program violates C++ rules in a way the standard does not define. The compiler is free to do anything: crash, produce wrong results, or appear to work correctly sometimes. Common causes include out-of-bounds access, use-after-free, signed integer overflow, and data races. Never rely on undefined behavior; use tools like AddressSanitizer and ThreadSanitizer to detect UB during testing. ## Example This example shows common undefined behavior pitfalls and safe alternatives. ```cpp // compile: g++ -O2 -o ub ub.cpp // run: ./ub // description: undefined behavior examples and safe alternatives #include #include #include void unsafe_buffer() { int arr[10]; // arr[100] = 5; // UB: out of bounds } void safe_buffer() { std::vector v(10); v.at(100); // safe: throws exception instead of UB } void unsafe_ptr() { int* p = nullptr; // *p = 5; // UB: null pointer dereference } void safe_ptr() { std::unique_ptr p = std::make_unique(5); // valid // use p safely } int main() { safe_buffer(); safe_ptr(); return 0; } ```