← Вернуться к курсу: C programming from scratch

Warnings and sanitizers: let the machine catch your bugs

Видео скоро появится

C lets you do almost anything, including reading memory that is not yours or adding until an integer overflows. When you do, the program does not always fail: sometimes it works "by luck" on your computer and breaks on another. That is called undefined behavior, and it is the source of the hardest C bugs. The good news is that the compiler and some tools called sanitizers detect most of these problems for you, at a minimal cost. In this lesson you learn to ask them for help from day one.

Compiler warnings

Always compile with gcc -std=c17 -Wall -Wextra -Wpedantic. -Wall enables the most useful warnings (unused or uninitialised variables, printf formats that do not match the type, assignments inside an if); -Wextra adds more checks, and -Wpedantic warns if you use extensions that are not standard C. Treat every warning as an error: if the compiler warns you, it is almost always right. To force it, add -Werror and the build will stop at any warning. Read them from top to bottom: the first one usually causes the others.

c
#include <stdio.h>

int main(void) {
    int unused_counter;       /* -Wunused-variable */
    int x;
    printf("%d\n", x);        /* -Wuninitialized: x has no value yet */

    long big = 3000000000L;
    printf("%d\n", big);      /* -Wformat: %d expects int, not long */

    if (x = 5) {              /* -Wparentheses: did you mean x == 5? */
        puts("assigned");
    }
    return 0;
}

This program compiles, but gcc with -Wall -Wextra shows four warnings and each one is a real bug: x is used with no value, a long is printed with %d (the correct format is %ld), a variable is unused and x = 5 assigns instead of comparing. Fixing them is trivial once warned; without the warning, you would have an intermittent failure that takes hours to find. If you truly want to ignore a variable, write (void)unused_counter; to show it is intentional.

Sanitizers: run-time errors

Some errors are not visible when compiling, only when running. That is what AddressSanitizer (ASan) and UndefinedBehaviorSanitizer (UBSan) are for. They are enabled by compiling with -fsanitize=address,undefined and -g (so messages show file and line). ASan watches every memory access: it detects writes outside an array, reads of already freed memory (use-after-free), double free and, when the program ends, memory leaks. UBSan detects signed integer overflow, division by zero, invalid shifts and other undefined operations. The program runs slower, so they are used during development and testing, not in the final version.

c
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *data = malloc(4 * sizeof *data);
    if (data == NULL) {
        return 1;
    }
    for (int i = 0; i <= 4; i++) { /* bug: should be i < 4 */
        data[i] = i * i;           /* ASan: heap-buffer-overflow at i == 4 */
    }
    printf("%d\n", data[3]);
    return 0;                      /* bug: missing free(data) -> leak report */
}
bash
gcc -std=c17 -g -fsanitize=address,undefined -fno-omit-frame-pointer bug.c -o bug
./bug
# ==12345==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x...
# WRITE of size 4 at 0x... thread T0
#     #0 0x... in main bug.c:10
# 0x... is located 0 bytes after 16-byte region [0x...,0x...)
# allocated by thread T0 here:
#     #0 0x... in malloc
#     #1 0x... in main bug.c:5

The ASan report gives you exactly what you need: the type of error (heap-buffer-overflow), whether it was a read or write, the line where it happened (bug.c:10) and the line where the memory was allocated (bug.c:5). "0 bytes after 16-byte region" means you wrote right after the end of the 16 bytes you asked for: it is the classic off-by-one error, i <= 4 instead of i < 4. Fix it, add free(data) before the return, and run again: the report disappears. With UBSan, an int x = INT_MAX; x = x + 1; produces "runtime error: signed integer overflow". Signed integer overflow is undefined in C, it does not "wrap around" as many believe.

  • Always compile with -std=c17 -Wall -Wextra -Wpedantic and fix every warning.
  • During development add -g -fsanitize=address,undefined.
  • ASan: buffer overflows, use-after-free, double free and leaks.
  • UBSan: signed overflow, division by zero, invalid shifts.
  • On Windows with MinGW the sanitizers may not be available: use WSL, Linux, macOS or Valgrind.

Проверьте себя

Вопрос 1 из 5

Which options enable gcc's most useful warnings?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →