Look at this code:
int i = 5;
i = i++ + ++i;
printf("%d\n", i);
What does it print? Different compilers can give different answers (even if the two you try happen to agree; current GCC and Clang both print 12), and the same compiler may give a different answer when optimization is turned on. None of them is "wrong", because the C standard gives this code no meaning at all.
We have already met this idea a few times: accessing an array out of bounds, using ++ twice on the same variable in one expression, left-shifting a negative number, and reading variadic arguments with the wrong type. All of these are examples of undefined behavior. In this topic we will see exactly what that term means, why C has it, the most common cases, and how to avoid them. It is one of the favourite topics in C interviews.
What is Undefined Behavior?
Undefined behavior (UB) is what happens when a program does something for which the C standard imposes no requirements.
Once a program has undefined behavior, anything is allowed. The program might:
appear to work correctly,
print a garbage value,
crash (for example, with a segmentation fault),
work today and fail tomorrow, on another machine, or with a different compiler option,
behave in ways that seem impossible from reading the code.
The most dangerous of these is the first one. Code with undefined behavior often seems to work during testing, which is why such bugs reach production.
Four Kinds of Behavior in C
The C standard sorts program behavior into categories. Knowing the difference is a classic interview question:
Kind | Meaning | Example |
|---|---|---|
Well-defined | The standard says exactly what happens |
|
Implementation-defined | Each compiler chooses, and must document its choice |
|
Unspecified | Several outcomes are allowed; the compiler need not document or be consistent | The order in which function arguments are evaluated |
Undefined | No requirements at all | Signed integer overflow, out-of-bounds access, dereferencing |
For example, in:
printf("%d %d\n", getA(), getB());
whether getA() or getB() runs first is unspecified. Both calls happen, and the program is still valid; you just cannot rely on the order. That is very different from undefined behavior, where the whole program loses its meaning.
Why Does C Have Undefined Behavior?
Other languages check array indexes, catch integer overflow, and throw errors for null references. C deliberately does not, for two reasons:
Speed. Checking every array access or every addition costs time. C trusts the programmer and skips these checks.
Portability. C runs on everything from tiny microcontrollers to supercomputers. Different hardware reacts differently to, say, an integer overflow or division by zero. By leaving such cases undefined, the standard does not force any processor to behave in one particular way.
There is also a third, less obvious effect: the compiler is allowed to assume that undefined behavior never happens, and it uses that assumption to optimize your code. We will see why this matters shortly.
Common Undefined Behaviors
1. Accessing an Array Out of Bounds
int marks[5] = {90, 80, 70, 60, 50};
for (int i = 0; i <= 5; i++) /* bug: should be i < 5 */
{
printf("%d\n", marks[i]); /* marks[5] does not exist */
}
C does not check array bounds. marks[5] reads whatever is in memory after the array, and writing to it can overwrite other variables. Writing past the end of an array is called a buffer overflow, and it has been the cause of many real security attacks. Functions like gets() (removed in C11) and careless strcpy() are classic sources.
2. Invalid Pointer Use
int *p = NULL;
*p = 10; /* dereferencing a null pointer */
int *q;
*q = 10; /* q is uninitialized: points to an unknown address */
int *r = malloc(sizeof(int));
free(r);
*r = 10; /* use after free (dangling pointer) */
free(r); /* double free */
All four are undefined behavior. Dereferencing NULL usually crashes on desktop systems, but the standard does not guarantee a crash.
Returning the address of a local variable is the same problem in disguise:
int *getNumber()
{
int n = 42;
return &n; /* n stops existing when the function returns */
}
3. Signed Integer Overflow
int x = INT_MAX; /* 2147483647 with a 32-bit int */
x = x + 1; /* undefined behavior */
Many people expect x to become -2147483648. On most machines it often does, but that is not guaranteed. Even C23, which now requires two's complement representation, still keeps signed overflow undefined.
Unsigned integers are different. Unsigned arithmetic is well-defined and wraps around modulo 2n, so UINT_MAX + 1u is always 0.
4. Division by Zero
int a = 10, b = 0;
int c = a / b; /* undefined behavior */
int d = a % b; /* also undefined */
A less known case: INT_MIN / -1 is also undefined, because the true answer (2147483648 with a 32-bit int) does not fit in an int. On x86 it typically crashes the program just like division by zero.
5. Modifying a Variable Twice Without Sequencing
C only guarantees the order of certain operations. Between two "sequence points" (for example, the end of a full statement, or the &&, ||, ?: and comma operators), you must not modify a variable twice, or modify it and also read it for another purpose.
i = i++ + ++i; /* UB: i modified more than once */
a[i] = i++; /* UB: i read for the index and modified */
printf("%d %d", i, i++); /* UB: i read and modified in the same call */
x = x++; /* UB */
The fix is simple: split the work into separate statements.
a[i] = i;
i++;
6. Using an Uninitialized Variable
int total; /* local variable, never given a value */
total = total + 5; /* reads an indeterminate value */
A local (automatic) variable starts with an indeterminate value, not 0. Reading it is undefined behavior in typical cases like this one. (Global and static variables are different: if you do not initialize them, they are automatically set to zero.)
7. Invalid Shifts
int a = 1 << 32; /* UB if int is 32 bits: shift count >= width */
int b = 1 << -1; /* UB: negative shift count */
int c = -1 << 2; /* UB: left shift of a negative value */
(Right-shifting a negative value is implementation-defined, not undefined.)
8. Modifying a String Literal
char *s = "hello";
s[0] = 'H'; /* UB: string literals must not be modified */
char t[] = "hello";
t[0] = 'H'; /* fine: t is an array copy that we own */
String literals are often stored in read-only memory, so the first version commonly crashes.
9. Wrong Format Specifier
printf("%d\n", 3.14); /* UB: %d expects an int, but a double was passed */
printf("%d %d\n", 5); /* UB: the second int was never passed */
As we saw in the Variadic Functions topic, printf() cannot check the types of its arguments, so it trusts the format string completely.
10. Using the Result of a Function That Did Not Return a Value
int getMax(int a, int b)
{
if (a > b)
return a;
/* forgot: return b; */
}
int m = getMax(2, 7); /* UB: no value was returned but it is used */
main() is the one exception: reaching its closing brace behaves like return 0; (since C99).
Quick Reference Table
Undefined behavior | Example | Safe alternative |
|---|---|---|
Out-of-bounds access |
| Keep indexes in |
Null / dangling pointer |
| Check for |
Signed overflow |
| Check against |
Division by zero |
| Check the divisor first |
Unsequenced modification |
| One change per variable per statement |
Uninitialized variable |
| Always initialize: |
Invalid shift |
| Shift unsigned values by less than the width |
Modifying a string literal |
| Use |
Wrong format specifier |
| Match specifiers to types; compile with |
Missing return value | Non-void function falls off the end | Return a value on every path |
How the Compiler Uses Undefined Behavior
This is the part that surprises most programmers. Consider a function that tries to detect overflow:
int willOverflow(int x)
{
return x + 1 < x; /* "if adding 1 made it smaller, it overflowed" */
}
The compiler reasons like this: "Signed overflow is undefined, so I may assume it never happens. If x + 1 never overflows, then x + 1 < x is always false." With optimization on (-O2), GCC and Clang compile this function to simply return 0;. The check you wrote is gone.
If x were unsigned int, the compiler could not do this, because unsigned wrap-around is well-defined.
Another example:
int getValue(int *p)
{
int value = *p; /* p is dereferenced first */
if (p == NULL) /* the compiler may delete this check */
return -1;
return value;
}
Because *p already ran, the compiler concludes that p cannot be NULL (otherwise the program would already have undefined behavior), so it may remove the if entirely. The correct code checks before dereferencing.
This is why a program with undefined behavior can work in a debug build (-O0) and break in a release build (-O2). The compiler is not buggy; the program is.
Writing Safe Code: Example
Here is a program that checks for problems before they happen, instead of after:
#include <stdio.h>
#include <limits.h>
/* Returns 1 and stores a + b in *result if it fits, otherwise returns 0 */
int safeAdd(int a, int b, int *result)
{
if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b))
{
return 0;
}
*result = a + b;
return 1;
}
/* Returns 1 and stores a / b in *result if the division is valid */
int safeDivide(int a, int b, int *result)
{
if (b == 0 || (a == INT_MIN && b == -1))
{
return 0;
}
*result = a / b;
return 1;
}
int main()
{
int r;
unsigned int u = UINT_MAX;
u = u + 1; /* unsigned: well-defined, wraps around to 0 */
printf("UINT_MAX + 1 = %u\n", u);
if (safeAdd(100, 200, &r))
printf("100 + 200 = %d\n", r);
if (!safeAdd(INT_MAX, 1, &r))
printf("INT_MAX + 1 would overflow\n");
if (safeDivide(17, 5, &r))
printf("17 / 5 = %d\n", r);
if (!safeDivide(10, 0, &r))
printf("10 / 0 is not allowed\n");
return 0;
}
Output:
UINT_MAX + 1 = 0
100 + 200 = 300
INT_MAX + 1 would overflow
17 / 5 = 3
10 / 0 is not allowed
The key idea in safeAdd(): instead of computing a + b and checking the result (too late, the overflow already happened), we rearrange the check so that nothing can overflow. If b is positive, a + b > INT_MAX is the same as a > INT_MAX - b, and INT_MAX - b is always safe to compute.
C23 adds ready-made checked arithmetic in <stdckdint.h>: ckd_add(), ckd_sub() and ckd_mul() compute the result and return true if it overflowed.
Tools That Catch Undefined Behavior
The compiler cannot catch every case, but these tools catch a lot. We will use some of them again in the Debugging topic.
Tool | What it catches |
|---|---|
| Compile-time warnings: wrong format specifiers, uninitialized variables, missing returns, unsequenced modifications |
| At runtime: signed overflow, invalid shifts, division by zero, misaligned pointers and more |
| At runtime: out-of-bounds access, use after free, double free |
Valgrind | Invalid memory reads/writes, use of uninitialized values, leaks |
For example, save this as overflow.c:
#include <stdio.h>
#include <limits.h>
int main()
{
int x = INT_MAX;
x = x + 1;
printf("%d\n", x);
return 0;
}
Compile and run it with UBSan (GCC or Clang):
gcc -g -fsanitize=undefined overflow.c -o overflow
./overflow
Instead of silently continuing, it reports the problem with the file and line number (line 7 here), in a message like:
overflow.c:7:7: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
This is GCC's message; Clang's wording is the same, but the column number can differ. By default the program then keeps running and prints -2147483648; add -fno-sanitize-recover=undefined to make it stop at the first error.
Common Misconceptions
"It printed the right answer, so it is correct." No. Undefined behavior can produce the expected output by luck.
"Signed overflow just wraps around." Not guaranteed. Only unsigned arithmetic wraps by rule.
"Dereferencing NULL always crashes." Usually, on desktop systems, but the standard promises nothing, and the optimizer may change what happens.
"There is a correct answer to
i = i++ + ++i." There is not. Any number your compiler prints is just one possible outcome."Undefined behavior only affects the line where it happens." Because the compiler optimizes based on the assumption that UB never happens, it can affect code before and after that line too.
Interview Tips
If asked for the output of code like
i = i++ + ++i;orprintf("%d %d", i, i++);, the best answer is: "This is undefined behavior, so there is no correct output. Different compilers may print different values." Then explain thatiis modified and read without sequencing.Be ready to explain the difference between undefined, unspecified and implementation-defined behavior with one example each.
Know that signed overflow is UB but unsigned overflow is well-defined. This is asked very often.
Mention tools: compiling with
-Wall -Wextraand testing with-fsanitize=undefined,addressshows practical experience.Explain why UB exists (performance and portability). Interviewers like hearing the reason, not just the rule.
In Simple Words
Undefined behavior means the C standard places no rules on what happens. The program may work, crash, or behave strangely, and the compiler is allowed to assume it never happens.
Remember the most common causes:
Array index out of bounds Signed integer overflow
NULL / dangling pointer use Division by zero
i = i++ + ++i style expressions Uninitialized local variables
Invalid shifts Modifying string literals
Wrong printf format specifier Missing return value
The golden rule: check before you act. Check indexes before accessing arrays, pointers before dereferencing, divisors before dividing, and ranges before adding. And let the compiler warnings and sanitizers help you find what you missed.