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
- Treat all external input as hostile. Validate length, range, format and encoding before use. Reject, do not "fix", anything unexpected.
- Know every buffer's size and pass it with the pointer. Use operations that take a size. See Buffer overflows.
- Check arithmetic before it feeds a size, index or allocation. Overflow in
count * sizehas caused many exploits. - Check every return value that can fail:
malloc,fopen,fread,snprintf,strtol, system calls. - Initialize everything, and free once. Clear sensitive data when finished.
- Prefer simple, small functions with clear ownership of memory. Complexity hides bugs.
- Compile with warnings and hardening and test with sanitizers and fuzzing.
Try it
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.
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. Avoidstrcpy,strcatandsprintfunless the sizes are proven. Givescanf("%s")a width or usefgets. - Never pass user-controlled text as a format string:
printf(user)lets an attacker read or write memory with%sand%n. Writeprintf("%s", user). - Do not build shell commands with
system()orpopen()from untrusted text; useexecv-style calls with separate arguments. See system and exec. - Convert numbers with
strtol/strtodand checkerrnoand the end pointer, not withatoi.
Memory
- Check
mallocforNULL. Set pointers toNULLafterfree. Free exactly once. - Use
callocor checked arithmetic for array sizes. - Clear secrets (keys, passwords) with a function the compiler cannot remove:
explicit_bzero(glibc, BSD),memset_explicit(C23) ormemset_s(Annex K). A plainmemsetright beforefreemay 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
intbecomes a hugesize_t. - Validate before narrowing conversions (
size_ttoint). - Remember the signed overflow rule: it is undefined, not wrap-around. See Integer overflow.
Files and the system
- Race conditions: checking a file with
accessorstatand then opening it leaves a window in which the file can be replaced (TOCTOU). Open first and check the open descriptor withfstat. UseO_EXCLwithO_CREATfor temporary files, ormkstemp. - Least privilege: drop privileges you do not need, close descriptors before
exec, and setO_CLOEXEC. - Do not trust environment variables such as
PATHandLD_LIBRARY_PATHin 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
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.
Related
- Buffer overflows, Undefined behavior catalog and Bounds-checked functions
- strtol, snprintf and stdckdint.h
- Tutorial: String safety and Best practices