Skip to content
Tutorials Center
My learning

Topics

Lesson 95 of 135 ยท Advanced C

Undefined Behavior

Understand undefined behavior in C - what the standard means by it, why optimizers exploit it, the most common causes, and the checks and tools that keep code safe.

The C standard describes what every correct program does. For a long list of mistakes, though, it deliberately says nothing at all: the behavior is undefined. Reading past the end of an array, overflowing a signed integer, dereferencing a null pointer, using memory after free: in each case the standard places no requirements on the result. The program may crash, print garbage, seem to work perfectly, or do something that contradicts the source code you wrote. It may also behave differently after you add an unrelated printf, change optimization level, or update your compiler.

This is the single most important idea for writing reliable C. Undefined behavior (UB) isn't a rare corner case: it's behind most crashes and most security holes in C programs. In this lesson you'll learn exactly what "undefined" means, why the optimizer makes it worse than "whatever the hardware does", the mistakes that cause nearly all of it, and the habits and tools that keep you on safe ground. You've already met many of these traps in earlier lessons, such as Integer Types, Arrays and Memory Errors; this lesson pulls them together.

Four kinds of "it depends"

The standard uses four different terms, and only one of them means "your program is broken".

Term What it means Examples
Implementation-defined Each compiler chooses a behavior and documents it sizeof(int), whether plain char is signed, right-shifting a negative number (before C23)
Unspecified One of several allowed behaviors; the compiler need not document which, and it may vary The order in which f(a(), b()) evaluates a() and b()
Locale-specific Depends on the current locale Whether isalpha accepts an accented letter
Undefined No requirements whatsoever Signed overflow, out-of-bounds access, use-after-free, null dereference

Implementation-defined and unspecified behavior are normal parts of C: your code is fine as long as it doesn't depend on one particular outcome. Undefined behavior is different. Once a program executes it, the standard says nothing about anything the program does, even the parts that ran before the faulty line (the compiler may have reordered them).

Note: "It worked when I tested it" proves nothing about UB. The same code can give the right answer with -O0, a wrong one with -O2, and crash on a different machine. Treat every instance of UB as a bug, even if you've never seen it misbehave.

Why the optimizer makes UB worse

It's tempting to think UB just means "the hardware does its natural thing". On x86, adding 1 to the largest int wraps to the smallest negative number, so surely INT_MAX + 1 is simply negative? Not in C. Because signed overflow is undefined, the compiler is allowed to assume it never happens, and it uses that assumption to simplify code.

C The compiler assumes signed overflow never happens

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.

This example deliberately executes UB, so its first line may differ between compilers and settings. With our GCC it prints 1 ("true"), even though a hardware addition would wrap to a negative number and make the comparison false. GCC reasoned: "x + 1 > x is true for every x where it is defined, and I may ignore the case where it isn't", and compiled the function to return 1;. No overflow ever happens at run time; the comparison simply disappeared.

That's the real danger. UB doesn't just produce one wrong value at one moment. The compiler's assumption that it cannot happen can delete safety checks, reorder statements and change loops far from the faulty line. Real security bugs have come from overflow checks such as if (offset + len < offset) that the optimizer was entitled to remove.

The unsigned line, by contrast, is perfectly defined: unsigned arithmetic wraps modulo 2โฟ, so it prints 2147483648.

The common causes

A short list of mistakes causes most UB in real C programs. Learn to spot each one.

Signed integer overflow

Any int, long or long long arithmetic whose mathematical result doesn't fit the type is undefined: +, -, *, ++, and also INT_MIN / -1 and INT_MIN % -1 (the true answer, 2147483648, doesn't fit). Converting an out-of-range value to a signed type is implementation-defined instead (GCC wraps), and unsigned arithmetic always wraps.

Out-of-bounds array access

C never checks indexes. a[i] with i outside 0 to n - 1 reads or writes whatever memory is there. Forming a pointer more than one element past the end is UB too, even without dereferencing it (one-past-the-end is allowed, as you saw in Pointer Arithmetic). Writing out of bounds is the classic buffer overflow.

Invalid pointers

  • Dereferencing a null pointer.
  • Using a pointer after the object is gone: after free (use-after-free), or after the function that owned a local variable has returned (a dangling pointer, see Pointers and Functions).
  • Calling free twice on the same pointer, or on a pointer that didn't come from malloc.
  • Misaligned access, such as treating (char *)buf + 1 as an int * and dereferencing it.

Reading uninitialized variables

A local variable without an initializer has an indeterminate value. Using it in a calculation is a bug, and in some cases (a local whose address is never taken) the standard calls it UB outright. The compiler may produce a different "random" value each time it's read, or assume the read never happens.

Bad shifts

Shifting by a negative amount or by the width of the type or more (1 << 32 for a 32-bit int) is UB. Left-shifting a negative value, or a positive one so that a bit lands in the sign bit, is UB too. Shift unsigned values when you work with bits, as the Bitwise Operators lesson recommends.

Unsequenced modifications

Modifying a variable twice, or modifying it and reading it for another purpose, without a sequence point in between is UB: i = i++;, a[i] = i++;, f(i++, i++). The Assignment and Increment lesson covers the rules. The fix is always to split the expression into separate statements.

Strict aliasing violations

The compiler assumes that pointers to different types (say float * and int *) don't point at the same memory, except through char pointers. Reading a float through an int * is UB and can produce stale values after optimization. Use memcpy or a union instead, as shown below and in Unions.

Other common ones

  • Modifying a string literal (char *s = "hi"; s[0] = 'H';).
  • Reaching the end of a non-void function without return and then using the result.
  • Calling a function through a pointer of the wrong type.
  • Passing the wrong type to printf (%d with a double).
  • Overlapping source and destination in memcpy or strcpy (use memmove).
  • A data race between threads.

Let the compiler warn you

Many UB patterns are visible at compile time, and -Wall -Wextra (which our editor uses) catches a good share of them. The function below is never called, so nothing undefined actually runs; press Run just to read GCC's warnings, which appear along with the output.

C Warnings that point at undefined behavior

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.

GCC reports three problems: operation on 'n' may be undefined [-Wsequence-point] on line 10, left shift count >= width of type [-Wshift-count-overflow] on line 11, and 'total' may be used uninitialized [-Wmaybe-uninitialized] on line 8. Every one of them is a real bug. That's why serious projects compile with -Wall -Wextra -Werror (warnings become errors) from the very first day; see Best Practices.

Warnings can't catch everything, though. An index computed at run time, a pointer freed in another function, or an overflow that depends on input are invisible to the compiler. For those you need defensive code and run-time tools.

Writing code that can't hit UB

The general technique: check before you act. Test whether an operation is valid using values that can't themselves overflow, and only then perform it.

C Checking arithmetic before doing it

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.

C23 makes the overflow checks much easier with <stdckdint.h>. ckd_add(&result, a, b), ckd_sub and ckd_mul compute the mathematically exact result, store it (wrapped) in *result, and return true if it didn't fit. They work with any integer types, even mixed ones, so you never have to write the limit tests by hand. (GCC and Clang have offered the same thing for years as __builtin_add_overflow.)

C C23 checked arithmetic with ckd_add

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.

The last check matters in practice. malloc(count * sizeof(double)) with a huge count wraps around (size_t is unsigned, so this isn't UB itself), allocates a tiny block, and the program then writes far past its end. Checking the multiplication first turns a security hole into a clean error. calloc(count, size) performs the same check internally, as covered in Dynamic Memory.

Reinterpreting bytes safely

To look at the bits of a float as an integer, copy the bytes with memcpy instead of casting pointers. Compilers recognize this idiom and turn it into a single register move, so it costs nothing.

C Type punning with memcpy instead of a pointer cast

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.

Habits that prevent most UB

  • Initialize every variable when you declare it, even if it's just = 0 or = NULL.
  • Keep sizes and indexes in size_t, check them against the array length, and pass the length together with every array (see Pointers and Arrays).
  • Set pointers to NULL after free, and give every allocation one clear owner who frees it.
  • Use unsigned types for bit manipulation, and check shift amounts.
  • One side effect per expression. i++ on its own line never surprises anyone.
  • Prefer bounded functions: snprintf, fgets, memmove, strtol with error checks (see Safe String Handling).
  • Check arithmetic on untrusted input with limit tests or ckd_add.

Tools that find UB at run time

Compilers can also insert checks into your program. These flags are for development and testing builds on your own machine; our online editor doesn't use them.

Terminal
# AddressSanitizer: out-of-bounds, use-after-free, double free, leaks
gcc -g -fsanitize=address -fno-omit-frame-pointer main.c -o app

# UndefinedBehaviorSanitizer: signed overflow, bad shifts, null deref, misaligned access...
gcc -g -fsanitize=undefined main.c -o app

# Both at once (the usual choice for test builds)
gcc -g -fsanitize=address,undefined main.c -o app && ./app

When the instrumented program hits a problem, it stops (or reports and continues, for UBSan) with a message naming the exact file, line and kind of error, for example "signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'". Running your test suite under sanitizers is the most effective way to find UB before your users do. Valgrind (valgrind ./app) finds many memory errors without recompiling. The Debugging C Programs lesson shows how to read their reports.

Two more flags change the language rules instead of checking them: -fwrapv makes signed overflow wrap like unsigned arithmetic, and -ftrapv makes it abort. They can be useful safety nets in legacy code, but code written for them isn't portable C, so don't rely on them in new code.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A program reads one element past the end of an array and prints the expected value in every test. What can you conclude?

    Undefined behavior has no guaranteed outcome. Seeming to work is one of the possible outcomes, and the most dangerous one.
  2. 2. Which of these operations is well defined in C?

    Unsigned arithmetic wraps modulo 2โฟ, so UINT_MAX + 1u is 0. The other three are undefined.
  3. 3. Why can GCC compile return x + 1 > x; to return 1;?

    For every x where the expression is defined, it's true. The compiler is allowed to ignore the overflow case entirely.
  4. 4. What is the safe way to read the bit pattern of a float as a uint32_t?

    memcpy copies the bytes without breaking the strict aliasing rule. A plain cast converts the value (1.5f becomes 1), not the bits.
  5. 5. Which compiler option adds run-time checks that report signed overflow with the file and line?

    UndefinedBehaviorSanitizer instruments the program. -Wall only produces compile-time warnings.

Summary

  • Undefined behavior means the standard places no requirements on the program; anything can happen, including "seems to work".
  • Implementation-defined and unspecified behavior are normal; UB is always a bug.
  • Optimizers assume UB never happens, so it can delete checks and change code far from the faulty line.
  • The usual causes: signed overflow, out-of-bounds access, null/dangling pointers, double free, uninitialized reads, bad shifts, unsequenced modifications, strict aliasing, data races.
  • Compile with -Wall -Wextra (and -Werror), check before you act, use ckd_add/ckd_mul (C23) for arithmetic on untrusted values, and memcpy for type punning.
  • Test with -fsanitize=address,undefined and Valgrind to catch what the compiler can't see.

Next: Debugging C Programs