Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Types and Literals

Undefined behavior in C

Concept page on undefined behavior in C: what it means, the most common causes (overflow, bad pointers, shifts, aliasing) and how to write defined code.

Undefined behavior (UB) means the C standard places no requirements on what a program does once a certain operation is executed. The program may crash, print something plausible, produce a wrong result, or seem to work until you change the compiler, the optimization level or an unrelated line of code. It is not an error the compiler is required to report.

UB matters most because optimizers assume it never happens. If your code contains a signed overflow, the compiler may delete a check that "can only be true after overflow". The bug is not confined to the line with the UB: it can change code before and after it. Because of that, this page shows the defined way to do each thing in its live examples, and the dangerous forms only as read-only code.

Try it

C Defined alternatives to common UB

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 Safe use of pointers and strings

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.

Common causes

The following all have undefined behavior. Each is shown as a read-only snippet because its output cannot be relied on:

C
int x = INT_MAX;  x + 1;              /* signed integer overflow */
int *p = NULL;    *p = 1;             /* null pointer dereference */
int a[3];         a[3] = 0;           /* out-of-bounds access (one past is OK to point to, not to access) */
int i = 1;        i = i++ + ++i;      /* unsequenced modifications of one object */
int v;            printf("%d", v);    /* reading an uninitialized automatic object (in some cases) */
int s = 1;        s << 32;            /* shift count >= width, or negative */
free(p); free(p);                     /* double free */
char *q = malloc(4); free(q); q[0];   /* use after free */
float f = 1e30f;  (int)f;             /* float-to-int conversion out of range */
const int c = 1;  *(int *)&c = 2;     /* modifying a const object */

Other typical sources: reading through a pointer of an incompatible type (see strict aliasing), calling a function through the wrong pointer type, memcpy with overlapping ranges, comparing pointers to different objects with <, using restrict falsely, reaching the end of a non-void function and using its result, passing a null pointer to strlen, and calling printf with a mismatched format specifier.

Usage notes

  • UB is not the same as implementation-defined behavior. Implementation-defined results are documented by the compiler and consistent (see that page). With UB, nothing is promised.
  • "It works on my machine" proves nothing. A different -O level, compiler version or surrounding code can change what an UB program does.
  • Compile with warnings (-Wall -Wextra) and read them. Many UB patterns are flagged.
  • Use the sanitizers when you can run locally: -fsanitize=undefined,address finds overflow, bad shifts, out-of-bounds and use-after-free at run time (see sanitizers).
  • Unsigned arithmetic is always defined (modulo 2^N), which is why hash functions and checksums use it.
  • Check before you act. Test the operands for the overflowing case, then do the operation, as in the first example.
  • Prefer checked helpers: ckd_add, ckd_sub, ckd_mul from <stdckdint.h> (C23) report overflow without UB.
  • A catalog of examples with defenses is on undefined behavior catalog.