Site Tools


wiki:cpp-undefined-behavior

Table of Contents

C++ Undefined behavior

Undefined behavior 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.

// compile: g++ -O2 -o ub ub.cpp
// run: ./ub
// description: undefined behavior examples and safe alternatives
 
#include <iostream>
#include <vector>
#include <memory>
 
void unsafe_buffer() {
    int arr[10];
    // arr[100] = 5;  // UB: out of bounds
}
 
void safe_buffer() {
    std::vector<int> 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<int> p = std::make_unique<int>(5);  // valid
    // use p safely
}
 
int main() {
    safe_buffer();
    safe_ptr();
 
    return 0;
}
wiki/cpp-undefined-behavior.md · Last modified: by 127.0.0.1