Loading...

C essentialsAdvanced Topics

Best practices, style & secure coding

10 min lesson

Next
  • Best practices are the habits and rules that make C code reliable, readable and secure, covering naming, formatting, error handling and memory discipline.
  • They matter because C gives you great power with little protection, so disciplined habits prevent most real-world bugs and security holes.
  • Think of best practices as the traffic rules of programming: they keep everyone moving safely and predictably, even when no one is watching.
  • Naming: use clear names like totalPrice and isReady; avoid single letters except for loop indices.
  • Formatting: consistent indentation, braces on every block, short functions and small files make code easy to read.
  • Secure coding: check every return value, validate input, avoid unbounded string functions, and never trust data from outside the program.
  • The computer will do exactly what you write, including dangerous things; good practices make the intent clear and the code safe.
  • The syntax of good practice is mostly small habits: const correctness, initialization at declaration, and checking for NULL and errors.
  • A realistic use: a function that copies user input with a length limit and returns an error code instead of crashing.
  • A surprising detail: most security bugs in C come from a small set of mistakes: buffer overflows, integer overflow, missing NULL checks and format string bugs.
  • The example program demonstrates several good habits together: const correctness, bounded copy, error checking, and clear naming.
Keep in mind
  • Write code for humans first; the compiler is only the first reader.
  • Check every return value and every buffer size; trust nothing from outside.
  • Prefer bounded functions like snprintf and strncpy over strcpy and sprintf.
  • Keep functions short, names clear, and braces on every block.
  • Good habits make great engineers. You are building them now!
main.c
#include <stdio.h>
#include <string.h>

// Copy src into dst with a size limit; return 0 on success, -1 on error
int safeCopy(char *dst, size_t dstSize, const char *src) {
    // Reject NULL inputs and zero-size destinations
    if (dst == NULL || src == NULL || dstSize == 0) {
        return -1;
    }
    // Copy at most dstSize - 1 characters, leaving room for '\0'
    strncpy(dst, src, dstSize - 1);
    // Guarantee null termination regardless of source length
    dst[dstSize - 1] = '\0';
    return 0;
}

int main(void) {
    // A fixed-size buffer for the name
    char name[8];
    // A longer source string to show truncation is safe
    const char *source = "Alexandria";

    // Use the safe copy and check the result
    if (safeCopy(name, sizeof name, source) != 0) {
        printf("copy failed\n");
        return 1;
    }
    // Print the truncated, safely terminated result
    printf("Name: %s\n", name);
    return 0;
}

What happens: Name: Alexand

Breaking it down

NULL and size checks

if (dst == NULL || src == NULL || dstSize == 0) return -1;

Rejects invalid inputs before touching memory. This prevents crashes and undefined behavior.

Bounded copy

strncpy(dst, src, dstSize - 1);

Copies at most dstSize - 1 characters so there is always room for the terminator. This avoids buffer overflow.

Forced terminator

dst[dstSize - 1] = '\0';

Guarantees the string ends properly even if the copy filled the buffer. Without this, printing reads past the end.

Checking the result

if (safeCopy(...) != 0) return 1;

The caller checks the error code. Ignoring return values is a common source of silent failures.

Safer alternatives

RiskySaferWhy
strcpystrncpy or snprintfBounds the copy
sprintfsnprintfPrevents overflow
getsfgetsCannot overflow
atoistrtolReports errors
malloc without checkCheck for NULLAvoids crash

A helpful analogy

Best practices are like traffic rules: they keep everyone moving safely and predictably, even when no one is watching. A good driver checks mirrors, signals and keeps a safe distance; a good C programmer checks return values, sizes and NULL pointers.

Nesting rules

  • 1.Always check return values from functions that can fail.
  • 2.Always pass the destination size to functions that write into a buffer.
  • 3.Always null-terminate strings after a bounded copy.
  • 4.Never trust input length or content; validate before using it.

Common mistakes

Using strcpy with unbounded input

Avoid

char buf[8]; strcpy(buf, user);

Use instead

snprintf(buf, sizeof buf, "%s", user);

strcpy does not know the buffer size and overflows if the source is longer. Use snprintf or strncpy with a limit.

Ignoring return values

Avoid

fopen("x", "r"); // not checked

Use instead

if (!(f = fopen("x", "r"))) { perror("fopen"); return 1; }

Ignoring failures leads to crashes or silent misbehavior. Check the result and handle the error.

Trusting user input length

Avoid

int n = atoi(argv[1]); int a[n]; // huge or negative

Use instead

long n = strtol(argv[1], NULL, 10); if (n <= 0 || n > 1000) { /* reject */ }

Unchecked input can cause huge allocations, negative sizes or crashes. Validate and set limits.

Quick tips

  • •Adopt a formatter like clang-format to keep style consistent.
  • •Run static analyzers like cppcheck and clang-tidy regularly.
  • •Turn on -Wall -Wextra -Werror in your builds.
  • •Try reducing the buffer size in the example to see truncation still stay safe.
  • •Read the CWE Top 25 list once; it names the mistakes to avoid.
Previous
Next