Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Concepts and Tools

Undefined behavior catalog in C

A catalog of common undefined behavior in C with the rule behind each, the safe alternative, and runnable defenses: checked arithmetic, bounds checks and safe punning.

Undefined behavior (UB) means the C standard places no requirements on what happens. The program may crash, print something plausible, silently corrupt data, or behave differently at -O0 and -O2. Worse, the compiler is allowed to assume UB never happens and optimize on that assumption, so a bug in one line can change code elsewhere. Behavior that "worked yesterday" proves nothing.

This page is a field guide: the most common kinds of UB, grouped by cause, each with the defense you should use instead. The definition and the difference between undefined, unspecified and implementation-defined behavior are explained in Undefined behavior. The examples below that show UB are read-only on purpose: their output is not reliable, so we do not run them.

The catalog

Arithmetic

C
int a = INT_MAX;
int b = a + 1;          /* UB: signed overflow */
int c = 10 / zero;      /* UB: division by zero (also INT_MIN / -1) */
int d = 1 << 32;        /* UB: shift count >= width of the promoted type */
int e = -1 << 1;        /* UB: left shift of a negative value */

Defense: check before you compute, use unsigned when wrap-around is what you want, or use the C23 ckd_add, ckd_sub and ckd_mul from <stdckdint.h>. See Integer overflow.

Memory

C
int arr[4];
arr[4] = 1;             /* UB: out-of-bounds write */
int *p = NULL;
*p = 1;                 /* UB: null dereference */
free(q); free(q);       /* UB: double free */
int *r = malloc(4);
free(r); *r = 1;        /* UB: use after free */
int x; int y = x + 1;   /* UB-prone: reading an indeterminate value */

Defense: keep the length next to every array, check allocations, set pointers to NULL after free, initialize everything, and run sanitizers (see Sanitizers).

Pointers and types

C
char buf[8];
int *m = (int *)(buf + 1);
*m = 1;                 /* UB: misaligned access (and an aliasing violation) */
float f = *(float *)&u32;  /* UB: strict aliasing violation */
int *a = &x, *b = &y;
long d = b - a;         /* UB: subtracting unrelated pointers */

Defense: copy bytes with memcpy to reinterpret a value (it compiles to a single move), and only subtract pointers into the same array. See Strict aliasing.

Evaluation order and objects

C
int i = 0;
i = i++ + 1;            /* UB: unsequenced modification */
printf("%d %d", i++, i++);   /* unspecified order of evaluation */
const int k = 1;
*(int *)&k = 2;         /* UB: modifying a const object */
char *s = "text";
s[0] = 'T';             /* UB: modifying a string literal */

Defense: modify an object at most once between sequence points, use char s[] = "text"; for a writable copy, and never cast away const to write.

Library contracts

C
printf("%d", 3.5);      /* UB: wrong conversion specifier */
memcpy(a, a + 1, 8);    /* UB: overlapping ranges (use memmove) */
strcpy(small, long_text);   /* UB: overruns the buffer */
tolower(-5);            /* UB: argument must be EOF or an unsigned char value */

Defense: match format specifiers (the compiler warns with -Wformat), use memmove for overlap, use bounded operations, and cast char to unsigned char before calling the ctype functions.

Try it

C Defending against overflow, shifts and division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Defending against bad pointers and type punning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Usage notes

  • UB is a property of the program, not of one run. A program with UB can pass every test and still be wrong; a compiler upgrade or optimization level may expose it.
  • Optimizers use UB. Because signed overflow "cannot happen", a check like if (x + 1 < x) may be removed entirely. Test for overflow before the operation.
  • Warnings are cheap evidence. Build with -Wall -Wextra -Wformat=2, treat warnings as errors in CI, and read the ones about uninitialized variables and sequence points.
  • Tools find what warnings cannot. Sanitizers (-fsanitize=address,undefined), Valgrind and fuzzing catch many cases at run time. See Sanitizers and Valgrind.
  • Unspecified and implementation-defined are different. The order of function arguments is unspecified (one of several valid results); the size of int is implementation-defined (documented by the compiler). Neither is UB, but both make code non-portable.
  • C23 narrowed a few cases, for example by requiring two's complement representation for signed integers, but signed overflow is still undefined.