C/C++ Arena

Undefined behavior in C and C++

What undefined behavior is, the common causes (overflow, out of bounds, use after free), and how sanitizers catch it.

Undefined behavior (UB) is code the language places no requirements on. The compiler is allowed to assume it never happens, so the result can be anything: a crash, a wrong answer, or code that works until you change the optimization level.

Common causes:

Defend with warnings (-Wall -Wextra), sanitizers (-fsanitize=address,undefined), and by checking before doing arithmetic that could overflow.

Example

#include <limits.h>
#include <stdio.h>

int safe_add(int a, int b, int *out) {
    if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) return 0;
    *out = a + b;
    return 1;
}

int main(void) {
    int r = 0;
    int ok = safe_add(INT_MAX, 1, &r);
    printf("%d\n", ok);
    ok = safe_add(2, 3, &r);
    printf("%d %d\n", ok, r);
    return 0;
}

Output:

0
1 5

Practice it