Undefined Behavior in C
Some C code compiles without a single error, runs fine on your computer, and then gives a different answer on your friend's computer, or only crashes during the exam demo. Very often the cause is undefined behavior (UB): code that breaks a rule of the C language, so the standard says anything may happen.
In this lesson you will learn what undefined behavior is, how it differs from unspecified and implementation-defined behavior, the most common examples beginners write, and the compiler options and habits that help you find and avoid it.
What You Will Learn
- What undefined behavior means in C.
- Undefined vs unspecified vs implementation-defined behavior.
- The most common causes of undefined behavior.
- Why UB is dangerous even when the program "works".
- How to write safe versions of risky code.
- Tools to detect UB: warnings, sanitizers and Valgrind.
Undefined Behavior in C Explained
Exam definition: Undefined behavior is behavior, upon use of an erroneous program construct or data, for which the C standard imposes no requirements. The program may crash, print wrong results, appear to work correctly, or behave differently each time or with each compiler. The compiler is not required to warn about it. Examples include accessing an array out of bounds, signed integer overflow and dereferencing a NULL pointer.
Memory trick: Undefined behavior is like crossing a railway track where there is no crossing. Many times nothing happens, so people think it's safe. But there is no rule protecting you, and one day a train comes. "It worked on my laptop" proves nothing.
Three kinds of "the standard doesn't fix the result"
| Kind | Meaning | Example |
|---|---|---|
| Undefined behavior | No rules at all; the program is wrong | int a[3]; a[5] = 1; |
| Unspecified behavior | One of several valid results; the compiler need not say which | Order in which f() + g() calls f and g |
| Implementation-defined | The compiler chooses and must document it | sizeof(int), right-shift of a negative number |
Common Examples of Undefined Behavior
Read these snippets, but don't use them. Each one compiles, and each one is wrong.
int a[5];
a[5] = 10; /* 1. out-of-bounds write (valid indexes: 0..4) */
int x;
printf("%d", x); /* 2. reading an uninitialized local variable */
int big = INT_MAX;
big = big + 1; /* 3. signed integer overflow */
int *p = NULL;
*p = 5; /* 4. dereferencing a NULL pointer */
int *q = malloc(sizeof *q);
free(q);
*q = 7; /* 5. use after free (dangling pointer) */
int i = 1;
i = i++ + 1; /* 6. modifying i twice without a sequence point */
char *s = "hello";
s[0] = 'H'; /* 7. modifying a string literal */
int z = 10 / 0; /* 8. division by zero */
int k = 1 << 40; /* 9. shifting by more than the type's width */
printf("%d", 3.5); /* 10. wrong printf format for the argument type */
Example 1: Safe Versions of Risky Operations
#include <stdio.h>
#include <limits.h>
/* Returns 1 and stores the sum if it fits in an int, otherwise 0 */
int safe_add(int a, int b, int *sum)
{
if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b))
return 0; /* would overflow: refuse */
*sum = a + b;
return 1;
}
/* Returns 1 and stores the element if the index is valid */
int safe_get(const int arr[], int size, int index, int *value)
{
if (index < 0 || index >= size)
return 0;
*value = arr[index];
return 1;
}
int main(void)
{
int marks[5] = {70, 82, 65, 90, 58};
int total = 0; /* initialized: never garbage */
int result, value;
if (safe_add(2000000000, 200000000, &result))
printf("Sum = %d\n", result);
else
printf("2000000000 + 200000000 would overflow an int\n");
if (safe_add(INT_MAX - 5, 5, &result))
printf("INT_MAX - 5 + 5 = %d\n", result);
if (safe_get(marks, 5, 3, &value))
printf("marks[3] = %d\n", value);
if (!safe_get(marks, 5, 5, &value))
printf("marks[5] is out of bounds, not read\n");
total += marks[0] + marks[4];
printf("total = %d\n", total);
return 0;
}
Output
2000000000 + 200000000 would overflow an int INT_MAX - 5 + 5 = 2147483647 marks[3] = 90 marks[5] is out of bounds, not read total = 128
Code Explanation
- 2,000,000,000 + 200,000,000 = 2,200,000,000, which is bigger than
INT_MAX(2,147,483,647 for a 32-bit int). Adding them directly would be signed overflow, which is undefined behavior. safe_addchecks before adding:a > INT_MAX - bmeans "a + b would go past INT_MAX".INT_MAX - bitself can't overflow whenbis positive, so the check is safe.- For
INT_MAX - 5and5, the sum is exactlyINT_MAX, which fits, so the addition is done. safe_getchecks the index against the array size before reading, somarks[5]is never touched.totalstarts at 0. Without= 0,total += ...would read an uninitialized value, which is undefined behavior.
How Undefined Behavior Hurts You
The compiler is allowed to assume UB never happens, and it uses that assumption to optimize. That's why UB can cause effects that look impossible:
int check(int x)
{
return x + 1 > x; /* "always true" if overflow never happens */
}
You expect: check(INT_MAX) == 0 (because INT_MAX + 1 wraps to a negative number)
Compiler: signed overflow is UB, so x + 1 > x must always be true
-> replaces the whole function with "return 1;"
Result: check(INT_MAX) returns 1 with -O2, and maybe 0 without optimization.
- The same source code gives different answers with different optimization levels or compilers.
- Out-of-bounds writes can silently change other variables, so the crash appears far from the real bug.
- Some UB (buffer overflows) is a security hole that attackers use.
Tools that catch UB
gcc -Wall -Wextra -g prog.c # warnings for many mistakes
gcc -fsanitize=address,undefined -g prog.c # stops at the exact bad line at run time
valgrind ./prog # finds invalid reads/writes, leaks (Linux)
Example 2: Defined Alternatives
#include <stdio.h>
#include <limits.h>
#include <string.h>
int main(void)
{
unsigned int u = UINT_MAX;
char word[] = "hello"; /* an array copy: safe to modify */
int i = 1;
char name[8];
u = u + 1; /* unsigned arithmetic wraps: DEFINED */
printf("UINT_MAX + 1 = %u\n", u);
word[0] = 'H'; /* modifying an array, not a literal */
printf("word = %s\n", word);
i++; /* one change per statement */
i = i + 1;
printf("i = %d\n", i);
strncpy(name, "Christopher", sizeof name - 1); /* never overflow the buffer */
name[sizeof name - 1] = '\0';
printf("name = %s\n", name);
return 0;
}
Output
UINT_MAX + 1 = 0 word = Hello i = 3 name = Christo
- Unsigned overflow is defined: it wraps around to 0. Only signed overflow is undefined.
char word[] = "hello";creates a modifiable array.char *s = "hello";points to a read-only literal.- Splitting
i = i++ + 1into separate statements removes the double modification. strncpywithsizeof name - 1copies at most 7 characters and we add the'\0'ourselves, so the 8-byte buffer is never overrun.
Important Points to Remember
- Undefined behavior = no rules; "it works on my PC" means nothing.
- Common causes: out-of-bounds, uninitialized variables, signed overflow, NULL/dangling pointers, i = i++, modifying literals, division by zero.
- Unsigned overflow is defined (wraps); signed overflow is undefined.
- Check before you act: bounds before indexing, limits before adding, NULL before dereferencing.
- Compile with -Wall -Wextra and test with -fsanitize=address,undefined.
- The compiler may optimize assuming UB never happens, causing "impossible" results.
Common Mistakes Beginners Make
| Mistake | Why it's UB | Fix |
|---|---|---|
for (i = 0; i <= n; i++) a[i] = 0; | Writes one element past the end | Use i < n |
int sum; sum += x; | Reads an uninitialized local | int sum = 0; |
printf("%d %d", i++, i++); | Two unsequenced changes to i | One change per statement |
| Returning the address of a local variable | The local is gone after return (dangling) | Return a value, use malloc or a static variable |
gets(buf) | No size limit: buffer overflow | fgets(buf, sizeof buf, stdin) |
Undefined Behavior Practice Questions
- What is undefined behavior in C?
- Give five examples of undefined behavior.
- Is unsigned integer overflow undefined? What about signed?
- What is the difference between undefined and implementation-defined behavior?
- Name two tools or options that help detect undefined behavior.
Show answers
- Behavior for which the C standard places no requirements; anything may happen, including appearing to work.
- Out-of-bounds array access, reading an uninitialized variable, signed overflow, NULL dereference, use after free (also i = i++, modifying a string literal, division by zero).
- Unsigned overflow is defined (it wraps modulo 2n); signed overflow is undefined.
- Undefined has no rules; implementation-defined has a result chosen and documented by the compiler (like sizeof(int)).
-Wall -Wextra,-fsanitize=address,undefined, Valgrind.
Coding Exercise
This function has two cases of undefined behavior. Find them and write a correct version that prints the average of the array.
double average(int a[], int n)
{
int sum; /* bug 1 */
int i;
for (i = 0; i <= n; i++) /* bug 2 */
sum += a[i];
return sum / n;
}
Show solution
Bug 1: sum is not initialized. Bug 2: i <= n reads a[n], one past the end. Also, sum / n is integer division, which is not UB but gives a wrong average.
#include <stdio.h>
double average(const int a[], int n)
{
int sum = 0;
int i;
for (i = 0; i < n; i++)
sum += a[i];
return (double)sum / n;
}
int main(void)
{
int marks[] = {70, 82, 65, 90};
printf("Average = %.2f\n", average(marks, 4));
return 0;
}
Average = 76.75
Quick Quiz: Undefined Behavior (MCQ)
-
Which of these is undefined behavior?
A)
unsigned u = UINT_MAX; u++;B)int x = INT_MAX; x++;C)int y = 5 / 2;D)char c = 'A'; -
For
int a[4];, which access is out of bounds?A)
a[0]B)a[3]C)a[4]D)a[2] -
When a program has undefined behavior, the compiler must:
A) Always give an error B) Always give a warning C) Nothing; it isn't required to diagnose it D) Fix the code
-
sizeof(int)being 4 on one system and 2 on another is:A) Undefined B) Implementation-defined C) A syntax error D) A runtime error
-
Which gcc option detects UB at run time?
A)
-O2B)-cC)-fsanitize=undefinedD)-E
Show answers
- B: signed overflow.
- C:
a[4]. - C: it isn't required to diagnose it.
- B: implementation-defined.
- C:
-fsanitize=undefined.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Undefined behavior | Standard imposes no requirements |
|---|---|
| Implementation-defined | Compiler chooses and documents |
| Unspecified | One of several valid results |
| Signed overflow | Undefined |
| Unsigned overflow | Defined: wraps around |
| Top causes | Out of bounds, uninitialized, NULL, i = i++ |
| Detect | -Wall -Wextra, -fsanitize, Valgrind |
Frequently asked questions
- What is undefined behavior in C?
- Code that breaks a language rule, so the C standard sets no requirements: it may crash, give wrong results or seem to work.
- Why is i = i++ undefined?
- Because i is modified twice without a sequence point between the changes.
- Why can UB give different results with optimization?
- The compiler assumes UB never happens and optimizes based on that assumption.
Remember
- UB = crossing where there's no railway crossing.
- Check first, then act: bounds, limits, NULL.
Next Topic
Next lesson: Debugging C Programs with GDB. You will use the GDB debugger to pause a program, inspect variables and find bugs step by step.