Skip to content
systemcoding.dev
Security

Turn On Compiler Warnings That Catch Security Bugs

A curated set of GCC and Clang warnings, from -Wformat=2 and -Wstringop-overflow to -Wvla and -Wconversion, that flag memory-safety bugs before they ship.

5 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, LLVM and CMake logos.

The compiler already knows about many of the bugs in this series. It sees the buffer that is eight bytes long and the string that is eleven, the printf whose argument is the wrong type and the integer comparison that mixes signed and unsigned. By default it says nothing about most of them, because warnings cost build time and annoy people with legacy code. Turning the right ones on is the cheapest security work available: no runtime cost, no code changes beyond fixing what it finds. This post gives a curated set of GCC and Clang flags for security, explains what each catches, shows a small program that trips several of them and then shows how to introduce them into a project that has thousands of existing warnings. Examples target GCC 15 and Clang 20 on Linux 6.12.

The base set

Start with the two umbrella flags, then add the ones that matter for security.

FlagCatches
-Wall -Wextrathe broad baseline: unused values, missing returns, sign compare, uninitialized variables
-Wformat=2format and argument mismatches, non-literal formats and -Wformat-security
-Wstringop-overflowwrites past a known-size destination in memcpy, strcpy and friends (on by default in GCC)
-Warray-boundsconstant out-of-range array indexes (on with -Wall at -O2)
-Wnull-dereferencepaths where a null pointer is dereferenced, needs -O2 and -fdelete-null-pointer-checks
-Wconversionimplicit narrowing and sign changes, such as size_t to int
-Wsign-conversionimplicit conversion between signed and unsigned
-Wvlaany variable-length array, the stack-clash and overflow source
-Wallocaany alloca call
-Wcast-qualcasting away const
-Wshadowa local that hides another, a common source of wrong-variable bugs
-Wundef#if on an undefined macro, which silently evaluates to zero
-Wformat-overflow=2 and -Wformat-truncation=2sprintf and snprintf outputs that may overflow or be cut
-Wstack-protectorfunctions the stack protector level leaves unprotected
-Wtrampolinesnested functions that need an executable stack

Add the error promotions that remove whole bug classes, because a warning that scrolls past in a long build log is not a defense:

Text
-Werror=format-security
-Werror=implicit-function-declaration
-Werror=int-conversion
-Werror=incompatible-pointer-types

GCC 14 made the last three errors by default for C, and Clang 16 did the same for implicit function declarations, so these lines document the intent and protect older compilers. An implicit declaration is a security bug waiting to happen: the compiler assumes the function returns int, so a pointer-returning function like malloc loses its upper 32 bits on 64-bit systems.

A program that trips several

warn.cc
#include <stdio.h>
#include <string.h>

static void show(char *s)
{
    printf(s);
}

int main(int argc, char **argv)
{
    char buf[8];
    int n = argc;
    unsigned int limit = 4;
    int i;

    strcpy(buf, "overflowing");
    if (n < limit)
        show(buf);
    char tmp[n];
    tmp[0] = (char)i;
    return tmp[0];
}

Compile it with the base set:

Text
gcc -std=c17 -O2 -Wall -Wextra -Wformat=2 -Wconversion -Wvla -Wshadow -c warn.c

GCC reports (the wording and the order vary with the version, and the output is trimmed):

Text
warn.c: In function 'show':
warn.c:6:5: warning: format not a string literal and no format arguments [-Wformat-security]
warn.c: In function 'main':
warn.c:17:5: warning: 'strcpy' writing 12 bytes into a region of size 8 overflows the destination [-Wstringop-overflow=]
warn.c:18:11: warning: comparison of integer expressions of different signedness: 'int' and 'unsigned int' [-Wsign-compare]
warn.c:20:10: warning: ISO C90 forbids variable length array 'tmp' [-Wvla]
warn.c:21:12: warning: 'i' is used uninitialized [-Wuninitialized]

Each line maps to a bug from this series: the format-string vulnerability, the overflow with a copy, the sign-compare that turns a negative argc into a huge unsigned value, the VLA with an attacker-chosen size and the uninitialized read. Five distinct bug classes were found by the compiler without running anything.

What each warning needs from you

  • **-Wformat=2 needs annotations.** Wrappers must carry __attribute__((format(printf, ...))), as the earlier post shows, or the check stops at the wrapper.

  • **-Wstringop-overflow and -Warray-bounds need optimization.** Their analysis uses the optimizer's knowledge of values, so they find far more at -O2 than at -O0. A debug-only build hides them.

  • **-Wnull-dereference needs -O2** and reports paths, which can include false positives when the code is correct but the compiler cannot prove it.

  • **-Wconversion is noisy.** Turn it on for the parts of the code that handle sizes and external input, and fix its reports with explicit casts that document intent or with wider types.

  • **-Wundef requires defined() or a default** in the #if, and it finds typos in feature macros, such as #if USE_SSLL.

Static analysis in the compiler

GCC's -fanalyzer (GCC 10 and later) is a static analyzer that follows paths through a function. In C it reports use-after-free, double free, null dereference, leaks, file descriptor misuse and some buffer overflows, with a path explanation. It is slow and prone to noise in large programs, so use it in a separate CI job and not in the developer build. Clang has --analyze and the scan-build driver, and clang-tidy has security-related checks, with names that vary by version, so consult its list for your release.

Rolling this out in an old project

Turning on everything on a codebase with ten thousand warnings gets you a revert. A plan that works:

  1. **Compile with -Wall -Wextra and read the count.** Save it. The aim is monotonic: the number never goes up.

  2. Promote the security-critical few first. -Werror=format-security, -Werror=implicit-function-declaration and -Werror=incompatible-pointer-types rarely fire in code that already builds on a current compiler, and they remove entire classes immediately.

  3. Apply stricter flags per directory or per target. New code and parsers get -Wconversion -Wvla -Wshadow, and legacy directories do not, until someone touches them. In CMake, use target_compile_options per target.

  4. Fix at the root. A warning from -Wstringop-overflow is a bug, not a style issue. Read it and fix the copy.

  5. Do not silence with casts or pragmas without a comment explaining why the code is right. A cast that hides a real narrowing is worse than the warning.

  6. Add a CI job that fails on new warnings, with a baseline file or by building with -Werror for the flags already clean.

Pragmas and suppression

When a warning is wrong, silence the narrowest scope. #pragma GCC diagnostic push, #pragma GCC diagnostic ignored "-Wstringop-overflow" and pop around one statement, with a comment, is acceptable. A file-wide or build-wide disable is a decision that should have a name next to it. System headers are already exempt from most warnings when included with -isystem, so use that for third-party code you cannot change.

What warnings cannot do

They see one function or one translation unit. They do not know the size of a buffer that arrives through a pointer parameter, a length that comes from a network packet or the invariant that makes a cast safe. A clean build is a floor: it means the obvious mistakes are gone. The sanitizers in the next subcluster, fuzzing and code review find the rest.

Also inToolchains
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.