# C/C++: runtime error: signed integer overflow / null pointer / shift exponent too large (UndefinedBehaviorSanitizer)

**Code:** `runtime error:` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

UBSan detected code that triggers undefined behaviour (overflow, null dereference, out-of-bounds index, bad shift, misaligned access) — the program may appear to work and still be wrong.

## Meaning

Undefined behaviour lets the optimiser assume it never happens, so bugs surface only at `-O2`, on other compilers, or after a compiler upgrade. UBSan reports `file:line:col: runtime error: <what>`. Fix each report rather than silencing it.

## Common causes

- Signed integer overflow (`INT_MAX + 1`)
- Null pointer dereference or member access through null
- Array index out of bounds or shift by a negative or too large count
- Misaligned access, invalid enum or bool value
- Division by zero or `INT_MIN / -1`

## Quick fix

1. Compile with `-fsanitize=undefined` and run your tests
2. Use wider or unsigned types, or check ranges before arithmetic
3. Add bounds and null checks

## Detailed fix by platform

### GCC / Clang

1. `g++ -g -fsanitize=undefined -fno-sanitize-recover=all main.cpp` stops at the first report
2. Combine with address: `-fsanitize=address,undefined`

### CMake

1. `target_compile_options(app PRIVATE -fsanitize=undefined)` and `target_link_options(app PRIVATE -fsanitize=undefined)`

## Code examples

### Checked arithmetic

```cpp
#include <climits>
#include <iostream>

int add_checked(int a, int b) {
    if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) {
        throw std::overflow_error("int overflow");       // instead of undefined behaviour
    }
    return a + b;
}

int main() { std::cout << add_checked(INT_MAX, 1) << "\n"; }
```

## How to diagnose

1. **Message** — Which kind of undefined behaviour?
2. **Line** — file:line:col from the report?
3. **Inputs** — Which values trigger it?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/ubsan-runtime-error)
