
Recall first from Understanding undefined behaviour
- Undefined behaviour is not a bug the CPU punishes; it is a licence for the compiler to assume the impossible never happens.
- Unspecified and implementation-defined behaviour are legal but vary; undefined behaviour is never safe.
- Signed overflow, out-of-bounds access, use-after-free, double free and data races are the systems UB to hunt first.
Warnings: the first line of defence
4 min readYou now know which constructs leave the language as undefined behaviour. This lesson answers how to catch and prevent them before the program runs: compiler warnings, defensive coding habits, and static analysis.
The cheapest tool is already installed. gcc and clang can diagnose thousands of suspicious constructs, but most of that checking is off by default. The three base flags switch on the bulk of it.
CFLAGS = -Wall -Wextra -Wpedantic
-Wall is a misnomer: it is not "all", it is a curated set of high-value warnings such as format-string mismatches and unused variables. -Wextra adds more, including comparisons that are always true and missing field initialisers. -Wpedantic insists on strict standard conformance and flags extensions. On top of these, four targeted flags catch the defects that matter in systems C.
CFLAGS += -Wconversion -Wshadow -Wformat=2 -Wstrict-prototypes
-Wconversion warns about implicit conversions that may change a value or its sign, the source of many truncation bugs. -Wshadow warns when an inner declaration hides an outer one, which makes you think you are changing one variable while changing another. -Wformat=2 makes the printf family checking stricter, including warning when a format string itself is not a literal. -Wstrict-prototypes warns about functions declared with an empty parameter list, such as int f(), which in C before C23 means "unspecified parameters" rather than "no parameters"; in C23 an empty list means no parameters, matching (void), but until then the flag keeps the two apart.
1turn on the base flags
Compile the same file with -Wall and read what appears. A format mismatch is the classic first catch.
/* warn.c */
#include <stdio.h>
int main(void) {
char *name = "learner";
printf("%d\n", name); /* %d expects int, but name is char * */
return 0;
}
gcc -Wall -o warn warn.c
Typical output (yours will differ):
warn.c: In function 'main':
warn.c:6:13: warning: format '%d' expects argument of type 'int',
but argument 2 has type 'char *' [-Wformat=]
2add the targeted flags
Add -Wconversion -Wshadow -Wformat=2 -Wstrict-prototypes and rebuild. Some warnings appear only at higher optimisation levels, because data-flow analysis such as use-of-uninitialised-variable needs -O1 or above to work. This is a reason to run your warning-clean build with optimisation on, not only at -O0.
3make warnings fatal in CI
-Werror turns every warning into a hard error, so a warning fails the build. Applied to your own code and in your test pipeline, it stops new warnings from accumulating.
CFLAGS = -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wformat=2 -Wstrict-prototypes -Werror
Two related traps are worth knowing. An implicit function declaration, calling a function without a prior prototype, has been a constraint violation since C99, but Ubuntu 24.04's gcc 13 only warns while gcc 14 turns it into an error; declare prototypes so your build behaves the same on both. And since gcc 10, -fno-common is the default, so an int x; that appears in two translation units is now a "multiple definition" link error rather than a silent merge.
Going deeperWhy -Werror is controversial in shipped code
Treating warnings as errors is the right habit for your own code, but it has a cost when applied to code you publish. A newer compiler release may add a new warning, or warn about something that was silent before, and a downstream build that used -Werror now breaks through no fault of the author. The common compromise is to develop and test with -Werror on, but not to ship -Werror in the defaults of a library or a build system others consume, or to pin the exact compiler version in the build environment. The goal is to catch warnings, not to make builds fragile.
warn.c: In function ‘main’:
warn.c:4:14: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char
*’ [-Wformat=]
4 | printf("%d\n", name);
| ~^ ~~~~
| | |
| int char *
| %s
learner@embeddex:~/lab$ # the buggy program still runs and prints the pointer as a decimal
learner@embeddex:~/lab$ ./warn
1556017156
learner@embeddex:~/lab$ # -Werror turns the warning into a failed build
learner@embeddex:~/lab$ gcc -Wall -Wextra -Wpedantic -Wconversion -Wshadow -Wformat=2 -Wstrict-p
rototypes -Werror -o warn warn.c
warn.c: In function ‘main’:
warn.c:4:14: error: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’
[-Werror=format=]
4 | printf("%d\n", name);
| ~^ ~~~~
| | |
| int char *
| %s
cc1: all warnings being treated as errorsDefensive coding and secure string handling
5 min readDefensive coding is a set of small, permanent habits rather than a single technique. Each one removes a whole class of bug.
Check every return code. malloc, calloc and realloc can fail and return NULL. Always test before use.
int *p = malloc(sizeof *p * n);
if (p == NULL) {
/* handle the failure; do not dereference p */
return -1;
}
On Linux this check is necessary but not sufficient: the kernel over-commits memory by default, so malloc may return a non-NULL pointer and the process is killed later by the out-of-memory killer when it touches the pages. Checking is still correct, because a NULL return must always be handled; it just does not guarantee the memory is physically present.
Use snprintf, not sprintf. sprintf writes without a size limit and will overflow the destination. snprintf takes the buffer size, never writes past it, and returns the number of characters that would have been written, so you can detect truncation.
char buf[16];
int needed = snprintf(buf, sizeof buf, "%s", src);
if ((size_t)needed >= sizeof buf) {
/* the output was truncated */
}
Bound-check every write. Before writing to an array, prove the index is in range, or the length fits. Prefer size_t for lengths and indices so a negative value cannot silently turn into a huge unsigned one.
Be const-correct. Mark parameters and local variables const when they are not modified. The compiler then rejects an accidental write, and the reader knows the function's contract.
Check integer overflow before it happens. gcc and clang provide checked builtins that return a flag instead of overflowing.
int a = INT_MAX, b = 1, sum;
if (__builtin_add_overflow(a, b, &sum)) {
/* overflow: handle it */
}
The same checked arithmetic is standardised in C23's <stdckdint.h>, and a manual test such as if (a > INT_MAX - b) works when the operands are non-negative.
The string library deserves special attention because it contains the most dangerous functions in C. gets is unfixable and was removed from the language in C11. strcpy and strcat copy with no destination size, so they overflow whenever the source is longer than the destination. The replacement is snprintf, or a bounded copy where you set the terminator yourself.
/* bounded copy that is always NUL-terminated */
size_t n = sizeof dst;
size_t len = strlen(src);
if (len >= n)
len = n - 1; /* reserve a byte for the terminator */
memcpy(dst, src, len);
dst[len] = '\0';
Going deeperThe strncpy trap
strncpy(dst, src, n) looks like the safe version of strcpy but is not. If src is longer than n, it copies n bytes and does not NUL-terminate dst, so the next function that reads dst as a string runs off the end. If src is shorter, it pads the rest of dst with NUL bytes, which wastes time on large buffers. It was designed for fixed-width fields in early filesystem directory entries, not for general strings. If you must use it, always write dst[n - 1] = '\0'; afterwards. Better, use snprintf(dst, n, "%s", src) or the explicit memcpy plus terminator above, whose behaviour is obvious.
The final habit is deciding which checks belong in the shipped program and which do not. A runtime check is code that always runs: it validates input that can be wrong at run time, such as a number read from a file or a device, and returns an error or a safe default. An a check that states an invariant the programr believes is always true, compiled out of the program when NDEBUG is defined is the opposite: it documents an internal invariant and aborts the program if it is violated.
#include <assert.h>
size_t clamp_index(size_t i, size_t n) {
assert(n > 0); /* the programr's invariant: n is never zero */
return i < n ? i : n - 1;
}
assert is controlled by NDEBUG. Define NDEBUG and every assert expands to nothing, so the expression inside is not evaluated. Never put a side effect inside an assert, because it vanishes in release builds. Use assert for bugs that are always wrong, and runtime checks for input that is merely untrusted.
The value that overflows your buffer is almost always read from outside: a command-line argument, a file, a packet, a sensor. Validate it once, at the point it enters the program, against explicit limits, and every later function can trust it. Centralising the check is cheaper than defending every use.
learner@embeddex:~/lab$ # build the bounded copy with snprintf
learner@embeddex:~/lab$ gcc -Wall -o sd snprintf_demo.c
snprintf_demo.c: In function ‘main’:
snprintf_demo.c:4:45: warning: ‘%s’ directive output truncated writing 11 bytes into a region of
size 8 [-Wformat-truncation=]
4 | int needed = snprintf(buf, sizeof buf, "%s", "hello world");
| ^~ ~~~~~~~~~~~~~
snprintf_demo.c:4:18: note: ‘snprintf’ output 12 bytes into a destination of size 8
4 | int needed = snprintf(buf, sizeof buf, "%s", "hello world");
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
learner@embeddex:~/lab$ # snprintf truncates to fit the buffer and reports the length it needed
learner@embeddex:~/lab$ ./sd
hello w (needed 11)Static analysis: the compiler and its friends read your code
3 min readA warning is a local observation: the compiler notices something odd on one line. the examination of source code without executing it, following control-flow paths to find defects such as leaks, null dereferences and dead code goes further by tracking values and paths across functions. Three tools cover the practical range, and a fourth, MISRA C, is a rule set rather than a tool.
gcc's -fanalyzer, available since gcc 10, runs inside the compiler and does interprocedural, path-sensitive analysis. It is strongest at finding leaks, use-after-free and double frees across function boundaries, exactly the bugs that a single-line warning misses.
/* leak.c */
#include <stdlib.h>
int work(int fail) {
int *p = malloc(sizeof *p);
if (fail)
return -1; /* p is never freed on this path */
free(p);
return 0;
}
gcc -fanalyzer -o leak leak.c
Typical output (yours will differ):
leak.c: In function 'work':
leak.c:7:9: warning: leak of 'p' [CWE-401] [-Wanalyzer-malloc-leak]
cppcheck is a standalone, free linter that does not need a full build and works on single files. It is fast and finds a different, pattern-based set of problems.
cppcheck --enable=all leak.c
clang-tidy is the Clang-based checker used as a preview here; the M2 tooling session returns to it properly. It is more configurable, running named checks against a compilation database.
clang-tidy leak.c -- -I.
The regulated-industry counterpart is MISRA C, a set of rules for writing C in safety-critical systems such as automotive and medical devices, where a compiler that can assume anything is unacceptable. MISRA bans or restricts exactly the constructs this lesson labels dangerous: it recommends a single point of exit per function (an advisory rule), forbids many implicit conversions, and restricts pointer arithmetic. It is not magic; it is a written-down subset of safe C, enforced by a checker. The full treatment is in module M19; here the takeaway is that the instincts you are learning now are the same instincts MISRA codifies.
learner@embeddex:~/lab$ gcc -o leak leak.c
learner@embeddex:~/lab$ # -fanalyzer follows the early return and reports the leaked p
learner@embeddex:~/lab$ gcc -fanalyzer -o leak leak.c
leak.c: In function ‘work’:
leak.c:5:16: warning: leak of ‘p’ [CWE-401] [-Wanalyzer-malloc-leak]
5 | return -1;
| ^
‘work’: events 1-4
|
| 3 | int *p = malloc(sizeof *p);
| | ^~~~~~~~~~~~~~~~~
| | |
| | (1) allocated here
| 4 | if (fail)
| | ~
| | |
| | (2) following ‘true’ branch (when ‘fail != 0’)...
| 5 | return -1;
| | ~
| | |
| | (3) ...to here
| | (4) ‘p’ leaks here; was allocated at (1)
|Key takeaways
- Compile with -Wall -Wextra -Wpedantic and treat every warning as a defect, with -Werror in CI.
- Checking return codes, bound-checking writes and preferring snprintf over strcpy removes whole classes of bug; assert documents internal invariants while runtime checks guard untrusted input.
- strncpy is not a safe strcpy: it may leave the destination unterminated or waste time padding; set the terminator yourself or use snprintf.
- Static analysis such as gcc -fanalyzer follows control-flow paths across functions and finds leaks and double frees that a single-pass warning misses.
Reflect
- Explain to a colleague, in two sentences: compile with -Wall -Wextra -Wpedantic plus targeted flags and explain what -Werror and -Wstrict-prototypes do.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Official docsGCC manual: options to request or suppress warnings
- Man pagesnprintf(3) - Linux man page
- Man pageassert(3) - Linux man page
Official documentation first. Links checked when the lesson was published.