Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Concepts and Tools

Secure coding in C

Practical secure coding rules for C: validate input, check arithmetic and allocations, avoid dangerous functions, handle errors, limit privileges and harden builds.

C gives you direct control over memory, and with it, many ways to make a program unsafe. Secure coding in C means writing code so that hostile input cannot make it read or write outside its objects, run arbitrary code, leak data or crash. The guidance below follows the spirit of the CERT C Coding Standard and similar secure-coding guides, expressed as habits you can apply to every function you write.

Think of three questions for each piece of data that arrives from outside the program (files, network, command line, environment, user input): How big can it be? What values can it have? What does my code do if it is wrong? Most vulnerabilities come from not asking.

Core habits

  1. Treat all external input as hostile. Validate length, range, format and encoding before use. Reject, do not "fix", anything unexpected.
  2. Know every buffer's size and pass it with the pointer. Use operations that take a size. See Buffer overflows.
  3. Check arithmetic before it feeds a size, index or allocation. Overflow in count * size has caused many exploits.
  4. Check every return value that can fail: malloc, fopen, fread, snprintf, strtol, system calls.
  5. Initialize everything, and free once. Clear sensitive data when finished.
  6. Prefer simple, small functions with clear ownership of memory. Complexity hides bugs.
  7. Compile with warnings and hardening and test with sanitizers and fuzzing.

Try it

C Strict parsing of untrusted numbers

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.

C Checked sizes and a bounds-checked message parser

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.

Rules of thumb

Strings and input

  • Never use gets. Avoid strcpy, strcat and sprintf unless the sizes are proven. Give scanf("%s") a width or use fgets.
  • Never pass user-controlled text as a format string: printf(user) lets an attacker read or write memory with %s and %n. Write printf("%s", user).
  • Do not build shell commands with system() or popen() from untrusted text; use execv-style calls with separate arguments. See system and exec.
  • Convert numbers with strtol/strtod and check errno and the end pointer, not with atoi.

Memory

  • Check malloc for NULL. Set pointers to NULL after free. Free exactly once.
  • Use calloc or checked arithmetic for array sizes.
  • Clear secrets (keys, passwords) with a function the compiler cannot remove: explicit_bzero (glibc, BSD), memset_explicit (C23) or memset_s (Annex K). A plain memset right before free may be optimized away.
  • Avoid variable-length arrays on the stack with sizes from input.

Integers

  • Do not mix signed and unsigned in comparisons; a negative int becomes a huge size_t.
  • Validate before narrowing conversions (size_t to int).
  • Remember the signed overflow rule: it is undefined, not wrap-around. See Integer overflow.

Files and the system

  • Race conditions: checking a file with access or stat and then opening it leaves a window in which the file can be replaced (TOCTOU). Open first and check the open descriptor with fstat. Use O_EXCL with O_CREAT for temporary files, or mkstemp.
  • Least privilege: drop privileges you do not need, close descriptors before exec, and set O_CLOEXEC.
  • Do not trust environment variables such as PATH and LD_LIBRARY_PATH in privileged programs.
  • Do not use rand() for tokens or keys. Use the operating system's random source (getrandom, /dev/urandom).

Signals and threads

  • Call only async-signal-safe functions in signal handlers. See sigaction.
  • Protect shared data with mutexes; data races are undefined behavior.

Build and test hardening

TEXT
gcc -std=c23 -O2 -Wall -Wextra -Wformat=2 -Wconversion -Wshadow \
    -fstack-protector-strong -D_FORTIFY_SOURCE=2 -fPIE -pie \
    -Wl,-z,relro,-z,now program.c -o program

Read-only. These flags catch many mistakes and make exploitation harder (stack canaries, checked library calls, randomized layout, read-only relocations). They are a safety net, not a replacement for correct code. Add AddressSanitizer and UndefinedBehaviorSanitizer to your test builds (Sanitizers), run fuzzers on parsers, and review code that handles untrusted input.