What Undefined Behaviour Is and Why C Has It
Undefined behavior means the C standard sets no rules for a program, so anything can happen. Learn what it is, why C keeps it, and how to stay out of it.

You write a C program, it compiles, it runs, and it prints the right answer. Then you change the compiler flags, or move to another machine, or add one unrelated line, and it prints something else. Nothing in the source is a typo. This is the experience that the phrase undefined behavior names, and it is one of the first things every C programmer has to understand. This post defines the term in plain words, shows the smallest programs that trigger it, explains why the language was designed this way, and gives you a short list of habits that keep you safe. It assumes you can read a basic C program, and it uses C17 with GCC 14 on Linux for the examples.
The definition in plain words
When you write a C program, you are writing instructions for an imaginary computer called the abstract machine that the C standard describes. For almost every construct the standard says what the abstract machine does. int x = 2 + 3; makes x equal to 5, and nothing about that depends on your hardware.
For a small set of constructs, the standard says the opposite: it places no requirements on what happens. Those constructs have undefined behavior. The wording is in the standard's definitions (ISO/IEC 9899:2011, section 3.4.3), and it means exactly what it says. The program might crash. It might print a wrong number. It might appear to work. It might do something different tomorrow. All of those are correct implementations, because the standard demands nothing.
This is different from an error message. A C compiler does not have to tell you that your program has undefined behavior, and usually cannot, because many cases depend on values known only at run time. The program compiles, it runs, and the problem hides.
The smallest examples
Here are four short programs, each of which has undefined behavior. They are deliberately boring, because the real ones look just as ordinary.
#include <limits.h>
#include <stdio.h>
int main(void) {
int a = INT_MAX;
int b = a + 1; // signed integer overflow
int arr[3] = {1, 2, 3};
int c = arr[3]; // read past the end of the array
int *p = NULL;
int d = *p; // dereference of a null pointer
int e;
int f = e + 1; // read of an uninitialized variable
printf("%d %d %d %d\n", b, c, d, f);
return 0;
}Each of the four marked lines is undefined. The first adds one to the largest int, a result that does not fit. The second reads the fourth element of a three-element array. The third reads through a pointer that points nowhere. The fourth uses a variable that was never given a value.
Note what is missing: there is no output block for this program. That is the point. A single execution of it could crash on the null dereference, and a compiler could just as validly remove all four statements, because the results are never meaningfully used. There is no "expected output" to show, because the standard defines none.
What "anything can happen" means in practice
People often hear "undefined behavior" and picture a crash. A crash is one of the nicer outcomes, because it is noticeable. The common outcomes fall into four groups.
It works as you expected. The compiler translated the code into the instruction a beginner would guess, and the hardware did the obvious thing. This is the most dangerous outcome, because it teaches you the code is fine.
It gives a wrong result that looks plausible. Reading past the end of an array returns whatever bytes sit there, a number that might be part of another variable. The program continues with a bad value, and the bug surfaces far from its cause.
It crashes. A null dereference on Linux hits an unmapped page, and the kernel sends SIGSEGV. The program ends with "Segmentation fault". That is the system catching the problem, not the language.
The compiler changes the program. The optimizer assumes undefined behavior never happens, so it may delete checks and reorder code based on that assumption. This is the case that surprises people most, and the guide to undefined behavior in C covers it in depth. Here is a short version:
#include <limits.h>
#include <stdio.h>
int is_safe_to_add_one(int x) {
return x + 1 > x; // intended as an overflow check
}
int main(void) {
printf("%d\n", is_safe_to_add_one(INT_MAX));
return 0;
}Compiled with GCC 14 and -O0, the addition wraps around, the comparison is false, and the program prints 0. Compiled with -O2, the compiler reasons that a signed x + 1 can never be less than x, because overflow would be undefined, so it replaces the whole function with return 1, and the program prints 1. The same source and the same input give two answers, and both are allowed.
0That is the -O0 output. The -O2 output is 1.
Why C was designed this way
It seems reckless for a language to leave behavior open. There are two reasons, one historical and one practical.
The historical reason is portability. C was designed to run on many kinds of hardware, and in the 1970s and 1980s the hardware disagreed about basic things. Some machines wrapped on signed overflow, some trapped, and some saturated. Some computers could not read an int from an odd address. Instead of choosing one machine's behavior and making all others emulate it slowly, the committee left those cases undefined, so each compiler could use the native, fast behavior. The language stayed close to the machine.
The practical reason is speed. If the compiler can assume certain things never happen, it can skip the code that would handle them. It does not need to insert a bounds check for every array access, test every pointer for null before every use, or make every addition handle overflow. C programs run fast partly because the language says "this is your responsibility" and trusts you. Languages that check these things at run time, such as Java, Python and Go, pay for the checks, and languages that check them at compile time, such as Rust, make you prove the code is safe.
The trade-off is explicit. C gives you control and speed, and takes away the safety net. Undefined behavior is the name for where the net used to be.
Undefined, unspecified and implementation-defined
Two similar terms are worth keeping apart, because they are not as dangerous.
An implementation-defined behavior is one where the compiler documents its choice. The number of bits in an int is an example. You can rely on the choice, as long as you stay with that compiler and platform.
An unspecified behavior is one where the standard lists a few allowed outcomes and does not say which will happen. The order in which the two arguments of f(g(), h()) are evaluated is unspecified. The program is still valid, and either order is acceptable.
Undefined behavior has no list at all. A later post compares the three terms in detail. For now, hold on to this: the first two are about getting a value you did not predict, and the third is about the program having no meaning.
The five habits that prevent most of it
You do not need to memorize the two hundred or so entries in the standard's list. A handful of habits avoids nearly all the trouble beginners hit.
Initialize every variable when you declare it. Write
int total = 0;, notint total;.Check array indexes and sizes before using them. Use
size_tfor sizes and compare the index against the length first.**Check pointers for
NULLbefore you dereference them,** and check them first, not after.Do not rely on integer overflow. If a calculation might exceed the type's range, check the operands before the operation, or use a wider type.
Do not use a pointer after the memory it points to is freed or goes out of scope. After
free(p), setp = NULL.
Two tools turn these habits into automatic checks. Compile with -Wall -Wextra, which makes GCC warn about uninitialized variables and many suspicious constructs. And build your tests with -fsanitize=address,undefined, which makes the program stop with a message at the first violation instead of carrying on:
ub.c:6:15: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'That line is the kind of message UndefinedBehaviorSanitizer prints. It names the file, the line and column, and the rule broken. The location depends on your own source, and the sanitizer is a testing tool, not something you ship.
Is every compiler warning about undefined behavior?
No. A compiler warning is a hint, not a proof. GCC's -Wall catches simple cases, such as an obviously uninitialized variable or an array index that is a constant past the end. It cannot catch an index computed from user input. The absence of warnings means the compiler did not notice a problem, not that none exists. The only reliable approach is the combination: write defensively, compile with warnings, and test with sanitizers.


