C Defensive Programming: AddressSanitizer & Static Analysis Masterclass
Welcome to Phase 20 (Chapter 57): C Defensive Programming โ AddressSanitizer & Static Analysis Masterclass! Defensive C programming eliminates security bugs before deployment. In this guide, you will master replacing unsafe string APIs, using compiler sanitizers (ASan), and automated static analysis.
| Unsafe Legacy Function | Safe Replacement | Reason for Security Upgrade |
|---|---|---|
gets(buf) | fgets(buf, size, stdin) | gets() has no size limit (Removed in C11). |
strcpy(dest, src) | strncpy() / strlcpy() | Prevents unbounded buffer copies. |
strcat(dest, src) | strncat() / strlcat() | Enforces destination bounds. |
sprintf(buf, fmt) | snprintf(buf, size, fmt) | Enforces buffer length boundaries. |
Compile with -fsanitize=address,undefined to catch memory leaks, out-of-bounds array reads, and use-after-free bugs at runtime with exact file line tracebacks!
Q1: What is the performance overhead of AddressSanitizer?
ASan typically adds ~2x CPU execution slowdown and ~2x memory overhead. Excellent for testing; disable in release production builds.
Q2: What is static analysis vs dynamic analysis?
Static analysis (`cppcheck`, `clang-tidy`) inspects source code without executing it. Dynamic analysis (ASan, Valgrind) monitors program execution at runtime.
Q3: How do you integrate cppcheck into a CI build pipeline?
Run `cppcheck --enable=all --error-exitcode=1 src/` in your build script to break automated builds on detected bugs.
Q4: What does UndefinedBehaviorSanitizer (UBSan) catch?
UBSan catches signed integer overflow, division by zero, null pointer dereferencing, and misaligned pointer access at runtime.
Q5: Why is strncpy() not completely safe by default?
If `src` length equals or exceeds buffer size, `strncpy()` does NOT append a null terminator `\0`! Always manually set `buf[size - 1] = '\0'`.