Skip to content
Tutorials Center
My learning

Topics

Lesson 107 of 135 ยท Advanced C

Secure C Coding

Learn the C bugs behind real security holes - buffer overflows, format string attacks and integer overflow - and the habits and CERT-style rules that prevent them.

C trusts you completely. It does not check array bounds, it does not stop you from printing someone else's memory, and it quietly wraps integers around. That trust is what makes C fast, and it is also why a large share of the serious security vulnerabilities in operating systems, browsers and network software are C bugs. An attacker rarely needs a clever exploit; they need one place where your program reads or writes memory it does not own.

This lesson walks through the three families of bugs that cause most of the damage: buffer overflows, format string bugs and integer overflow. For each you'll see how the bug happens, why it is dangerous, and the small, boring habit that prevents it. Along the way you'll meet the style of rules published by CERT's secure C coding standard (INT, ARR, STR, FIO and others), which are worth reading once you finish. It helps to know undefined behavior, string safety and memory errors first.

Some snippets in this lesson are deliberately unsafe. They are shown in read-only blocks. Never run them, and never copy them into real code.

Why insecure code is exploitable

Think about a function that reads a name into a fixed array. The compiler places that array in a stack frame next to other data: other local variables, the saved frame pointer and the return address.

flowchart TB
    A["higher addresses"] --> B["return address"]
    B --> C["saved frame pointer"]
    C --> D["other locals (flags, counters)"]
    D --> E["char name[16]"]
    E --> F["lower addresses"]

A simplified stack frame: writing past the end of name runs into whatever sits above it.

The exact layout differs between compilers, platforms and optimization levels, and modern systems add defenses (stack canaries, non-executable stacks, address randomization). Those defenses raise the bar but do not remove the bug. The only reliable fix is to never write outside an object's bounds in the first place.

Buffer overflows

A buffer overflow happens when a program writes past the end of an array (or reads past it, which leaks data). The classic cause is a function that does not know the size of its destination:

C
char name[16];
gets(name);                    /* removed from C11: no way to limit input */
strcpy(name, argv[1]);         /* copies until it finds '\0', however long */
sprintf(name, "user-%s", id);  /* writes as much as the format produces */

None of these calls can know that name holds 16 bytes, so a 40-byte input writes 24 bytes of someone else's memory. In the best case the program crashes; in the worst case the attacker controls what gets written and where.

The cure is to pass sizes everywhere and use functions that honor them:

  • Prefer fgets (never gets) for reading lines.
  • Prefer snprintf(buf, sizeof buf, ...) over sprintf. It never writes more than sizeof buf bytes, always terminates the string, and returns the length the full result would have had, so you can detect truncation.
  • If you copy with memcpy, check length <= capacity first.
  • Be careful with strncpy: it does not guarantee a terminating '\0', and it pads short strings with zeros. It was designed for fixed-width records, not as a "safe strcpy".
C Detecting truncation with snprintf

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Notice that the function rejects input that does not fit rather than silently chopping it. Silent truncation is not always safe: truncating a file path or a user name can turn one valid value into a different valid value.

Off-by-one errors

A very common overflow is only one byte. A string of 15 characters needs 16 bytes with its '\0'. A loop that runs i <= n instead of i < n writes a[n]. Because the damage is small, the bug often survives testing and then shows up later as a corrupted neighbor variable. Write bounds as "index must be less than size" every time, and use sizeof array / sizeof array[0] instead of repeating a number.

Out-of-bounds reads

Reading past the end of an array is also a security bug. The famous Heartbleed flaw was exactly this: a length field supplied by the other side of a connection was trusted, and the program copied that many bytes from a smaller buffer, leaking secrets from the memory behind it. The lesson: a length that comes from outside your program is untrusted input, so validate it against the real size of the buffer before using it.

Format string bugs

printf reads its first argument as a program that says how many further arguments to expect and how to interpret them. If an attacker controls that first argument, they control the program:

C
char *message = get_user_input();
printf(message);                 /* BUG: message is used as the format */
printf("%s", message);           /* correct: message is just data */

If the input is %x %x %x %x, the first call prints values from the stack that you never passed. %s can crash the program by dereferencing garbage as a pointer, and %n writes a count of printed characters into memory, which can turn the bug into an arbitrary write.

The rule is simple: never let untrusted text be a format string. Always write printf("%s", text), fputs(text, stdout) or puts(text). Compilers help here: GCC and Clang warn about non-literal format strings with -Wformat-security (also in -Wall -Wformat=2 setups), and the attribute __attribute__((format(printf, 1, 2))) makes your own logging functions checkable as well.

C Data is not a format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Integer overflow

Integers are the quiet source of many overflows. Unsigned arithmetic wraps around by definition: UINT_MAX + 1 is 0. Signed overflow is undefined behavior, so the compiler may assume it never happens and delete your checks. In both cases the dangerous pattern is a size calculation that overflows, producing a number that is too small:

C
size_t count = read_count_from_network();
int *items = malloc(count * sizeof *items);   /* count * 4 can wrap to a tiny number */
for (size_t i = 0; i < count; i++) {
    items[i] = read_item();                    /* writes far past the small allocation */
}

On a 32-bit size_t, a count of 0x40000001 times 4 wraps to 4, so malloc happily returns four bytes and the loop writes over a billion ints into the heap. Another variant is the signed/unsigned mix: a negative int passed as a length becomes a huge size_t.

flowchart LR
    A["attacker-chosen count"] --> B["count * size wraps to a small value"]
    B --> C["malloc returns a small block"]
    C --> D["loop trusts the original count"]
    D --> E["heap overflow"]

An overflowing size calculation turns a harmless-looking allocation into a heap overflow.

The fix is to check before you calculate. C23 provides checked arithmetic in <stdckdint.h>: ckd_add, ckd_sub and ckd_mul return true when the mathematically correct result does not fit in the destination type, and store the wrapped result otherwise. If your compiler lacks it, test with division or compare against SIZE_MAX, as in the second function below.

C Checked arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A few more integer habits:

  • Use size_t for sizes and indices that come from sizeof, strlen or malloc, and don't mix it with int unless you have checked the range.
  • Validate that a signed value is non-negative before converting it to an unsigned length.
  • Turn on -Wall -Wextra -Wconversion -Wsign-compare; they flag many of these conversions.
  • Beware abs(INT_MIN) and -INT_MIN: the result does not fit in int.

Validate every input

Everything that crosses a trust boundary is input: command-line arguments, environment variables, files, network data and even the return values of library functions. Parse it with functions that report failure (strtol with errno and endptr, not atoi), check ranges, and reject anything unexpected instead of trying to repair it. Prefer allow-lists ("only digits, at most 9 characters") over deny-lists ("no semicolons").

Also remember the rest of the toolbox:

  • Initialize variables; reading an uninitialized value can leak old data.
  • Check the result of malloc, fopen, fread, fwrite and fclose.
  • Set a pointer to NULL after free, and never free twice (see dynamic memory).
  • Avoid system() with user-provided text; it hands your input to a shell. Use execve-style calls with an argument array instead (see fork, exec and pipes).
  • Wipe secrets such as passwords with a function the optimizer cannot remove (memset_explicit in C23, explicit_bzero on many systems), because a plain memset before free may be optimized away.

Tools and CERT-style rules

You don't have to find these bugs by eye. Use the compiler and runtime checkers:

Tool What it catches
-Wall -Wextra -Wformat=2 -Wconversion suspicious formats, sign and size conversions
-fsanitize=address (ASan) stack, heap and global overflows, use-after-free
-fsanitize=undefined (UBSan) signed overflow, bad shifts, null dereference
-fstack-protector-strong, -D_FORTIFY_SOURCE=2 runtime hardening against stack smashing
Valgrind, static analyzers leaks, uninitialized reads, taint paths

The CERT C Coding Standard organizes advice into short numbered rules, for example INT30-C (ensure unsigned integer operations do not wrap), ARR38-C (guarantee that library functions do not form invalid pointers), STR31-C (guarantee that storage for strings has sufficient space) and FIO30-C (exclude user input from format strings). Each rule shows a noncompliant example and a compliant fix. The rules are guidelines, not magic, but the habit they build is the right one: for every buffer, know its size; for every number, know its range; for every input, decide what is allowed.

Compile your tests with -fsanitize=address,undefined during development. Sanitizers turn silent memory corruption into an immediate, readable error message with a line number. See debugging for more.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is printf(user_text) dangerous?

    The first argument of printf controls how the other arguments are read. Attacker-controlled text can request arguments that were never passed. Use printf("%s", user_text) or fputs instead.
  2. 2. What does snprintf(buf, sizeof buf, "%s", s) return when s does not fit?

    snprintf never writes more than the given size and always terminates the buffer, and its return value is the untruncated length. If it is greater than or equal to the buffer size, the output was cut off.
  3. 3. Which line is the best defense against an overflowing allocation size?

    The multiplication can wrap to a small number, so check it before allocating. ckd_mul reports overflow without undefined behavior.
  4. 4. Why is signed integer overflow worse than unsigned wrap-around?

    Unsigned arithmetic is defined to wrap modulo 2^N. Signed overflow is undefined, so the optimizer may assume it never happens and delete code that tries to detect it.
  5. 5. Which statement about strncpy(dst, src, n) is true?

    If src has n or more characters, strncpy copies n bytes and writes no terminator. That is why careful code uses snprintf or checks lengths and adds the terminator itself.

Summary

  • Most C security holes are out-of-bounds writes or reads; always carry a buffer's size with the pointer and check it.
  • Replace gets, strcpy and sprintf with fgets and snprintf, and check for truncation instead of ignoring it.
  • Never pass untrusted text as a format string; write printf("%s", text).
  • Check size arithmetic before allocating, using ckd_mul/ckd_add from <stdckdint.h> or a division test; mind signed/unsigned mixes.
  • Treat all outside data as hostile: parse with strtol, validate ranges, prefer allow-lists.
  • Build with warnings, sanitizers and hardening flags, and use CERT's numbered rules as a checklist.

Next: Project: Calculator, where you can apply careful input handling in a complete program.