Show contents
Chapter 4 of 7 · 20 min
Undefined behaviour and sanitizers
By the end of this chapter, you'll be able to
- Define undefined behaviour and name its most common sources
- Detect out-of-bounds accesses and memory errors with AddressSanitizer
- Detect signed integer overflows with UndefinedBehaviorSanitizer
- Use a debugger to trace a crash back to its cause
What the standard doesn't guarantee
The C standard describes precisely what a correct program does. For some faulty operations, it promises nothing: that's undefined behaviour. The most frequent cases:
- reading or writing outside the bounds of an array;
- using memory after
free, or freeing twice; - dereferencing a null or uninitialised pointer;
- reading an uninitialised variable;
- overflowing a signed integer (
INT_MAX + 1); - dividing by zero, shifting an integer by more than its width.
The compiler optimises on the assumption that these cases never happen. It can therefore remove a check it considers useless or reorder the code. That's why the symptom often appears far from the cause, and changes with the optimisation level.
AddressSanitizer: memory errors
Built with -fsanitize=address, the program watches every memory access. At the first forbidden access, it stops and shows the faulty line. On this site, every C example is built this way:
#include <stdio.h>
int main(void) {
int grades[3] = {12, 15, 9};
int sum = 0;
for (int i = 0; i <= 3; i++) { /* <=: one pass too many */
sum += grades[i];
}
printf("%d\n", sum);
return 0;
}
Without a sanitizer, this program often displays a random number, sometimes the right one, and almost never crashes: the bug goes unnoticed. With AddressSanitizer, it stops immediately:
ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd...
READ of size 4 at 0x7ffd... thread T0
#0 in main average.c:7
The report gives the type of error (overflowing an array on the stack), the operation (a 4-byte read, an int) and the line.
The first forbidden access stops the program and points to the faulty line.
Text description of the animation
- The loop reads one slot too many: grades[3] doesn't exist.
- Built normally, the program contains no checks.
- The read takes whatever is lying around in memory: a wrong result, different from machine to machine. The bug stays hidden.
- With AddressSanitizer, every memory access is checked.
- The first forbidden access stops the program and points to the faulty line.
UndefinedBehaviorSanitizer: forbidden calculations
-fsanitize=undefined detects the other kinds of undefined behaviour, notably signed integer overflows:
#include <limits.h>
#include <stdio.h>
int main(void) {
int visits = INT_MAX;
visits = visits + 1;
printf("%d\n", visits);
return 0;
}
counter.c:6:21: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
For a counter that can grow very large, use a wider type (long long), check the limit before adding, or an unsigned type, whose overflow is defined (it wraps round to zero).
The debugger
When a program crashes, a debugger such as gdb lets you stop it at the moment of the fault and inspect the variables. Build with -g to keep the line numbers:
$ gcc -g -O0 average.c -o average
$ gdb ./average
(gdb) run
Program received signal SIGSEGV, Segmentation fault.
0x... in main () at average.c:7
(gdb) print i
$1 = 1052
(gdb) backtrace
#0 main () at average.c:7
print displays a variable, backtrace the stack of calls that led there, break sets a breakpoint. Valgrind (valgrind ./program) also detects memory errors and leaks, without rebuilding, but slowing execution down a lot.
Your turn
Worked exercise
Worked exercise: the moving average
This function computes the average of each group of 3 consecutive values of an array. AddressSanitizer reports an overflow. Find the bug, explain it, fix it, then check that the averages of {10, 20, 30, 40, 50} are 20.0 30.0 40.0.
void moving_averages(const double *v, int n, double *out) {
for (int i = 0; i < n; i++) {
out[i] = (v[i] + v[i + 1] + v[i + 2]) / 3;
}
}
Hint 1
i = n - 1, which indices of v does the line read? Do they exist?Hint 2
n - 2, and out only needs n - 2 slots.Show the solution and common mistakes
#include <stdio.h>
/* Writes n - 2 averages into out. Returns how many, or 0 if n < 3. */
int moving_averages(const double *v, int n, double *out) {
if (n < 3) return 0;
for (int i = 0; i + 2 < n; i++) {
out[i] = (v[i] + v[i + 1] + v[i + 2]) / 3;
}
return n - 2;
}
int main(void) {
double values[] = {10, 20, 30, 40, 50};
double averages[3];
int count = moving_averages(values, 5, averages);
for (int i = 0; i < count; i++) {
printf("%.1f%s", averages[i], i + 1 < count ? " " : "\n");
}
return 0;
}
20.0 30.0 40.0
With i < n, the last two passes read v[5] and v[6], outside the array, and write into out[3] and out[4], which don't exist either. The condition i + 2 < n guarantees that the last index read, i + 2, stays within bounds.
Common mistakes:
- Only fixing the read (
i < n - 2) while keeping anoutarray of sizen: it works, but the caller doesn't know how many slots are valid. Returning the number of results makes the function honest. - Writing
i < n - 2with annof typesize_t: ifnis 1,n - 2wraps round and becomes a huge number. Withi + 2 < n, no subtraction can go below zero.
Summary
- 1Undefined behaviour: the standard guarantees nothing, and the compiler assumes it never happens.
- 2Frequent sources: out-of-bounds access, use after free, null pointer, uninitialised variable, signed integer overflow.
- 3AddressSanitizer detects memory errors, UndefinedBehaviorSanitizer forbidden calculations.
- 4gdb stops the program at the moment of the fault; build with -g to keep the lines.
- 5A program that "works on my machine" isn't proven correct: always test with sanitizers.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.