Skip to main content
Be Bitwise
CSecurity-Focused C

Secure Coding in C

C hands you direct access to memory. That same gift hands you direct access to catastrophic bugs. Buffer overflows, format string vulnerabilities, integer overflows: these are behind the lion's share of security vulnerabilities ever found in systems software. Writing secure C demands discipline, an inventory of the usual traps, and the assumption that everything is out to get you.

The CERT C Coding Standard

The CERT C Coding Standard is a doorstop of rules and recommendations for writing secure C, spanning everything from string handling to concurrency. The sections below cover the areas where its rules pull the most weight: strings, format strings, integer overflow, input validation and the handling of secrets.

Safe String Handling

strcpy and strcat hold the title of most dangerous functions in the C standard library. Zero bounds checking. They will cheerfully scribble all over whatever lives past your destination buffer:

c
// DANGEROUS: strcpy does not check bounds
char buf[8];
strcpy(buf, "This string is way too long for the buffer");
// Buffer overflow! Overwrites stack memory

Safe alternatives:

c
#include <stdio.h>
#include <string.h>
// Option 1: snprintf (available everywhere)
char buf[8];
snprintf(buf, sizeof(buf), "%s", user_input);
// Always null-terminates, truncates if necessary
// Option 2: strlcpy (BSD, need to implement on Linux)
// strlcpy(buf, user_input, sizeof(buf));
// Option 3: strncpy + manual null termination
// strncpy zero-pads short input but does NOT terminate on truncation,
// so the second line is mandatory
strncpy(buf, user_input, sizeof(buf) - 1);
buf[sizeof(buf) - 1] = '\0';
Key Concept

Always use sizeof(buf) instead of hard-coding a number. If the buffer changes size, your bounds check follows automatically. snprintf is the safest pick: it always null-terminates and returns how many characters would have been written, so you can spot truncation when it happens.

Format String Vulnerabilities

User input as a format string? Hard no:

c
// VULNERABLE: user controls the format string
char *user_input = get_input();
printf(user_input); // If input is "%x %x %x", leaks stack data
// If input is "%n", writes to memory!
// SAFE: user input is always a format argument
printf("%s", user_input);

%n writes the number of bytes printed so far into a memory location pointed to by the corresponding argument. Hand an attacker control of the format string and you've handed them the ability to write arbitrary data to arbitrary addresses.

Integer Overflow Prevention

Signed integer overflow is undefined behaviour in C. Unsigned overflow wraps cleanly modulo 2^N. Both routes lead to security holes:

c
// VULNERABLE: integer overflow
size_t nmemb = get_user_count(); // e.g., 0x1000000000000001
size_t size = sizeof(struct item); // e.g., 16
size_t total = nmemb * size; // 2^64 + 16: a 64-bit size_t wraps to 16
// (with a 32-bit size_t, 0x10000001 does the same)
void *buf = malloc(total); // Allocates tiny buffer
// Writing nmemb items overflows the buffer

Safe multiplication:

c
#include <stdint.h>
#include <stdlib.h>
// Check for multiplication overflow
int safe_multiply(size_t a, size_t b, size_t *result) {
if (a != 0 && b > SIZE_MAX / a) {
return -1; // Would overflow
}
*result = a * b;
return 0;
}
// Or use calloc, which checks internally
void *buf = calloc(nmemb, size); // Returns NULL on overflow

Input Validation

Every byte of external input is a possible attack vector. Validate early. Reject anything that smells off:

c
// Validate array index
int process_item(int *array, size_t array_len, size_t index) {
if (index >= array_len) {
return -1; // Out of bounds
}
return array[index];
}
// Validate string length
int process_name(const char *name) {
size_t len = strlen(name);
if (len == 0 || len > 255) {
return -1; // Invalid length
}
// Process name...
return 0;
}
// Validate numeric ranges
int set_port(const char *port_str) {
char *end;
errno = 0;
long port = strtol(port_str, &end, 10);
if (errno != 0 || end == port_str || *end != '\0') {
return -1; // Out of range, no digits, or trailing junk ("80abc")
}
if (port < 1 || port > 65535) {
return -1; // Invalid port
}
return (int)port;
}

Avoiding Dangerous Functions

DangerousSafe AlternativeWhy
gets()fgets()gets has no length limit
strcpy()snprintf()No bounds checking
strcat()snprintf()No bounds checking
sprintf()snprintf()No bounds checking
scanf("%s")scanf("%255s")No bounds checking
atoi()strtol()No error detection

Null Pointer Checks

Dereferencing a null pointer is undefined behaviour. Check return values, every time:

c
FILE *f = fopen(path, "r");
if (f == NULL) {
perror("fopen");
return -1;
}
void *p = malloc(size);
if (p == NULL) {
fprintf(stderr, "Out of memory\n");
return -1;
}

Secure Memory Handling

Sensitive data — passwords, keys, anything secret — should be wiped from memory the moment it stops being needed:

c
#include <stdio.h>
#include <string.h>
void process_password(const char *password) {
char local_copy[256];
snprintf(local_copy, sizeof(local_copy), "%s", password);
// Use the password...
authenticate(local_copy);
// Clear sensitive data with a wipe the compiler must keep
explicit_bzero(local_copy, sizeof(local_copy));
}

A plain memset here is dead code as far as the compiler can tell (the buffer goes out of scope straight afterwards), so the optimiser is entitled to delete it. explicit_bzero (glibc and the BSDs), memset_s (C11 Annex K, provided by macOS), SecureZeroMemory (Windows) and C23's memset_explicit all exist to make the wipe stick. The older trick of zeroing through a volatile char * usually survives too, but the standard doesn't promise it.

Principle of Least Privilege

A secure program should:

  1. Drop privileges the moment you can: Need root to bind port 80? Bind first. Then drop to an unprivileged user.
  2. Shrink the attack surface: Don't link libraries you don't actually use.
  3. Fail closed: When something unexpected lands, deny access — never grant it by default.
  4. Validate at trust boundaries: Every function receiving external data validates it. "The caller should have validated" is famous last words.

A memorised blacklist of dangerous functions only gets you so far. Secure C comes from a mindset where every input is hostile and every assumption gets earned.

Challenges

Write a safe_copy function that copies a source string into a fixed-size destination buffer without overflow. Use snprintf. Test it with a string longer than the buffer and print the result.

C (GCC 9.2.0)