Undefined Behavior, Security & Debugging – C
Recognizing and avoiding buffer overflows and other pitfalls, and tracking them down with sanitizers, Valgrind and gdb.
Undefined behavior (UB) means: the standard places no requirements at all. The program may work, crash, deliver wrong results or – in the case of security vulnerabilities – give attackers control. Worse: optimizing compilers may assume that UB never occurs and therefore remove code. "It worked on my machine" proves nothing.
- Accessing outside of arrays (even just by one: "off-by-one") and buffer overflows
- Reading uninitialized variables
- Dereferencing
NULLor dangling pointers; use-after-free; double free - Overflow of signed integers (
INT_MAX + 1) - Division by 0; shifting by too many bits
- Modifying the same variable several times without a sequence point (
i = i++ + 1) - Wrong
printfformats (%dwith adouble)
// DO NOT RUN! Every line is a classic mistake.
int a[3]; a[3] = 1; // Off-by-one
char buf[8]; strcpy(buf, "way too much text");// Buffer overflow
int x; printf("%d\n", x); // uninitialized
int *p = malloc(4);free(p); *p = 1; // Use-after-free
free(p); // Double free
int i = INT_MAX; i++; // Signed overflow
printf(nutzereingabe); // Format string vulnerabilityA buffer overflow on the stack can overwrite the return address – the attacker redirects the program flow. The countermeasures are simple, but they require discipline: carry sizes along, check lengths, use functions that take a size.
#include <stdio.h>
#include <string.h>
#include <limits.h>
// Safe copying: returns 0 on success, -1 if truncated
int kopiere(char *ziel, size_t groesse, const char *quelle) {
if (groesse == 0) return -1;
size_t n = strlen(quelle);
int ok = 0;
if (n >= groesse) { n = groesse - 1; ok = -1; }
memcpy(ziel, quelle, n);
ziel[n] = '\0';
return ok;
}
// Detect overflow BEFORE the addition
int sicher_addiere(int a, int b, int *ergebnis) {
if ((b > 0 && a > INT_MAX - b) || (b < 0 && a < INT_MIN - b)) return -1;
*ergebnis = a + b;
return 0;
}
int main(void) {
char buf[8];
int rc = kopiere(buf, sizeof buf, "way too much text");
printf("%s (rc=%d)\n", buf, rc); // way too (rc=-1)
int summe;
printf("%d\n", sicher_addiere(INT_MAX, 1, &summe)); // -1
printf("%d\n", sicher_addiere(20, 22, &summe)); // 0
printf("%d\n", summe); // 42
char eingabe[] = "50%s%s"; // NEVER use user data as the format
printf("%s\n", eingabe); // correct: fixed format string, data as argument
return 0;
}There are excellent tools for tracking down errors. AddressSanitizer (ASan) reports memory errors with line numbers, UBSan detects overflows and faulty shifts, Valgrind (Linux) finds leaks, and on macOS leaks helps. A debugger (gdb, on macOS: lldb) lets you step through the code line by line:
# Build with sanitizers and run (debug build)
gcc -g -O0 -Wall -Wextra -fsanitize=address,undefined -fno-omit-frame-pointer -o test test.c
./test
# Memory leaks (Linux) and macOS respectively
valgrind --leak-check=full ./test
leaks --atExit -- ./test
# Debugger
gcc -g -O0 -o prog prog.c
gdb ./prog # macOS: lldb ./prog
# break main breakpoint run start
# next one line step step into a function
# print x show value bt call chain (backtrace)
# quit exit-fsanitize=address,undefined, run your tests with it, and treat warnings as errors (-Werror). Static analysis (clang-tidy, cppcheck) and assert(...) from <assert.h> also help for assumptions that must never be violated.-O2 can make UB visible: code that "works" with -O0 suddenly behaves differently when optimized. This is not a compiler bug – the program was already wrong before. Fix the cause instead of turning off the optimization.