Skip to content
systemcoding.dev
Fundamentals

15 Kinds of Undefined Behaviour in C With Examples

A cheat sheet of 15 kinds of undefined behavior in C, each with an example, the sanitizer message, the safe fix and when it is not a problem.

7 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the C, Zig and Rust logos.

The C standard lists around two hundred situations as undefined behavior in Annex J.2, but fifteen of them cause nearly every real bug. This cheat sheet goes through those fifteen. Each entry gives a short example, the rule in C11 it breaks, what UndefinedBehaviorSanitizer or AddressSanitizer prints, the safe replacement, and a line on when not to worry, because several of these have a legal twin that looks almost the same. Section numbers refer to ISO/IEC 9899:2011, and the sanitizer messages come from GCC 14 and Clang 19 on Linux. The line and column in a message depend on your source, so treat the numbers in the examples as placeholders.

Keep two facts in mind while reading. First, none of these is guaranteed to crash, and several are guaranteed to be optimized under the assumption that they never happen. Second, the sanitizers report only what your tests execute. A clean run is evidence, not proof.

1. Signed integer overflow

An arithmetic result that does not fit a signed type is undefined (6.5p5). That covers +, -, *, unary - and ++ on int, long and the other signed types.

c
int x = INT_MAX;
int y = x + 1;     // undefined
Text
runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'

Fix: check first (if (x > INT_MAX - 1)), use __builtin_add_overflow or C23 ckd_add, or do the arithmetic in an unsigned type. When not to worry: unsigned arithmetic wraps by definition, so UINT_MAX + 1u is 0u. And code built with -fwrapv has defined wrapping, which suits legacy code but not new code.

2. Division or remainder by zero

a / 0 and a % 0 are undefined for integers (6.5.5p5).

c
int d = 0;
int q = 10 / d;    // undefined
Text
runtime error: division by zero

Fix: test the divisor before dividing. When not to worry: floating-point division by zero is defined when the implementation claims IEEE 754 support (Annex F) and yields infinity or NaN. It is a different problem, not a crash.

3. INT_MIN divided by minus one

The true result of INT_MIN / -1 is 2147483648, which does not fit in a 32-bit int, so it is undefined, and so is INT_MIN % -1 (6.5.5p6). On x86-64 the idiv instruction faults and the process receives SIGFPE.

c
int a = INT_MIN, b = -1;
int q = a / b;     // undefined
Text
runtime error: division of -2147483648 by -1 cannot be represented in type 'int'

Fix: reject the pair (INT_MIN, -1) before dividing, and do the same for abs(INT_MIN). When not to worry: with a wider type such as long long the quotient fits, and a divisor known to be positive can never trigger it.

4. Shifting by too much

Shifting by a negative count, or by a count greater than or equal to the width of the promoted left operand, is undefined (6.5.7p3).

c
int n = 32;
unsigned m = 1u << n;   // undefined for a 32-bit unsigned
Text
runtime error: shift exponent 32 is too large for 32-bit type 'unsigned int'

Fix: validate 0 <= n && n < 32, or mask with n & 31 when you want the wrapped count. When not to worry: a constant count within the width, such as 1u << 31, is fine.

5. Left-shifting a value that does not fit

E1 << E2 on a signed E1 is undefined if E1 is negative, or if the result does not fit in the type (6.5.7p4). So 1 << 31 is undefined for a 32-bit int, while 1u << 31 is defined.

c
int bit = 1 << 31;      // undefined for 32-bit int
Text
runtime error: left shift of 1 by 31 places cannot be represented in type 'int'

Fix: shift unsigned values and write constants with a u suffix. When not to worry: C23 and recent compilers treat some signed left shifts more kindly, but code that must build with C11 should not depend on it.

6. Out-of-bounds array access

An index outside 0..n-1 is undefined, and forming a pointer more than one past the end is undefined even if unused (6.5.6p8).

c
int a[4] = {1, 2, 3, 4};
int v = a[4];           // undefined
Text
runtime error: index 4 out of bounds for type 'int [4]'

Fix: compare the index with the length first, keep the length next to the pointer, and prefer size_t indexes. When not to worry: the pointer one past the last element may be computed and compared, as in for (p = a; p != a + 4; p++). It must not be dereferenced.

7. Dereferencing a null pointer

Reading or writing through a null pointer is undefined (6.5.3.2p4).

c
int *p = NULL;
int v = *p;             // undefined
Text
runtime error: load of null pointer of type 'int'

Fix: check for NULL before the first use, and check first, since a use ahead of the check lets the compiler delete the check. When not to worry: free(NULL) is defined and does nothing, and taking &*p or &p->member in a context where nothing is read is a gray area best avoided.

8. Using a dangling pointer

After free, or after the object's lifetime ends (a returned pointer to a local), the pointer value is indeterminate and using it is undefined (6.2.4p2).

c
int *p = malloc(sizeof *p);
free(p);
*p = 1;                 // undefined
Text
ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000010

Fix: set p = NULL after free, never return the address of a local, and make ownership explicit. When not to worry: storing a freed pointer without using it is harmless, and realloc is fine as long as you use the returned pointer.

9. Double free or invalid free

Passing free a pointer that was already freed, or one that did not come from malloc, calloc, realloc or aligned_alloc, is undefined (7.22.3.3).

c
char *s = malloc(8);
free(s);
free(s);                // undefined
Text
ERROR: AddressSanitizer: attempting double-free on 0x602000000010

Fix: null the pointer after freeing, and free each allocation from exactly one owner. When not to worry: free(NULL) twice is fine.

10. Reading an uninitialized variable

An automatic variable that is never assigned holds an indeterminate value, and using it is undefined for most types (6.3.2.1p2).

c
int total;
total += 5;             // undefined
Text
warning: 'total' is used uninitialized [-Wuninitialized]

Fix: initialize at declaration, int total = 0;. When not to worry: objects with static storage start as zero, and a char array may be read through unsigned char to copy bytes without interpreting them.

11. Violating strict aliasing

Accessing an object through an lvalue of an incompatible type is undefined (6.5p7), for example reading a float through a uint32_t *.

c
float f = 1.0f;
uint32_t u = *(uint32_t *)&f;     // undefined

There is no standard sanitizer for it, and -Wstrict-aliasing catches only simple cases.

Fix: memcpy(&u, &f, sizeof u), which compilers reduce to a register move, or a union in C. When not to worry: character types, unsigned char included, may alias anything, and so may a struct containing the member you access.

12. Misaligned access

Converting a pointer to a type with stricter alignment, when the address is not suitably aligned, is undefined (6.3.2.3p7).

c
char buf[8];
uint32_t v = *(uint32_t *)(buf + 1);    // undefined
Text
runtime error: load of misaligned address 0x7ffd5c1e3b01 for type 'uint32_t', which requires 4 byte alignment

Fix: copy with memcpy, or declare the buffer with the alignment you need. When not to worry: x86-64 tolerates most misaligned loads in hardware, but the language rule still applies, so do not rely on it.

13. Modifying a string literal or a const object

Changing a string literal (6.4.5p7) or an object defined const (6.7.3p6) is undefined.

c
char *s = "hello";
s[0] = 'J';             // undefined

On Linux this segfaults, because the literal lives in a read-only page.

Fix: use char s[] = "hello"; for a writable copy, and const char * for pointers to literals. When not to worry: modifying a non-const object through a pointer to const is fine, only when the object itself was not defined const.

14. Unsequenced modifications

Modifying the same scalar twice between sequence points, or reading it while modifying it, is undefined (6.5p2).

c
int i = 1;
i = i++ + 1;            // undefined

GCC warns operation on 'i' may be undefined [-Wsequence-point].

Fix: split the expression into separate statements. When not to worry: &&, ||, ?: and the comma operator have a sequence point after their first operand, so i++ && i++ is defined.

15. Data race

Two threads accessing the same non-atomic object, at least one writing, without synchronization, is undefined (5.1.2.4p25).

c
int counter;                       // shared, plain int
void *worker(void *arg) { counter++; return arg; }
Text
WARNING: ThreadSanitizer: data race

Fix: use _Atomic int, a mutex or a thread-confined design. When not to worry: data written once before the threads start, then only read, needs no lock, and volatile does not substitute for either tool.

How to use the list

Treat the list as a review checklist. For each function that handles integers, indexes, pointers, memory lifetimes or threads, run down the fifteen and ask which could apply. Then run your tests under -fsanitize=address,undefined, and under -fsanitize=thread if you use threads, to confirm the answer.

The entries cluster into five groups: arithmetic (1 to 5), memory bounds and lifetime (6 to 9), initialization (10), type and representation rules (11 to 13) and evaluation order and concurrency (14 and 15). When a bug report says "only at -O2" or "only on ARM", start with whichever group matches the symptom.

Share

Keep reading

Flat illustration of user space above the system call boundary, the kernel and the hardware, with the C, FreeBSD and Linux logos.
Systems Programming

How argc and argv Reach main in a C Program

The kernel copies argc and argv onto the new process's stack on execve, then startup code hands them to main. See the layout and measure it with a program.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.