Course contentsShow
← C
Lesson 1148 of 1,21916. Practice and ProjectsFree lesson

The philosophy of 'Trust No One'

The philosophy of 'Trust No One'

What you'll learn: You will understand why a secure program assumes that every piece of external data is a potential threat to the system's stability.

The "Vending Machine" Mindset

Imagine you are designing a vending machine. If you "trust" the user, you assume they will only insert crisp, valid dollar bills. But in the real world, people try to insert taped-together coins, folded paper, or even flat metal washers to trick the machine. If your machine blindly accepts everything shoved into the slot, it will jam or be robbed.

In C programming, Defensive Programming is the art of building that vending machine. The "Trust No One" philosophy means your code should never assume that input from a user, a file, or a network is formatted correctly or fits within your memory limits.

Why C is particularly "Trusting"

C is a powerful language because it stays out of your way. If you tell C to copy 100 characters into a box that only holds 10, C will try to do it, likely crashing your program or opening a security hole (a buffer overflow).

To write defensive code, you must act like a skeptical bouncer at a club. Before you let any data into your program's "inner sanctum," you must verify its ID:

  1. Is it too long?
  2. Is it the wrong type (letters where numbers should be)?
  3. Is it empty or "Null"?

Code Example: The Skeptical Input

Instead of blindly trusting a number provided by a user, we check it before it can do any damage.

#include <stdio.h>

void process_age(int age) {
    // Defensive Check: Don't trust that 'age' is a realistic human number
    if (age < 0 || age > 120) {
        printf("Error: Invalid age provided. Access denied.\n");
        return;
    }

    printf("Age verified. Proceeding with registration...\n");
}

int main() {
    int user_input;
    
    printf("Enter your age: ");
    // Check if scanf even succeeded in finding a number
    if (scanf("%d", &user_input) != 1) {
        printf("Error: That isn't even a number!\n");
        return 1;
    }

    process_age(user_input);
    return 0;
}

By adding these checks, you ensure that the rest of your program's logic operates on "clean" data. You aren't being paranoid; you are being professional. By assuming the worst about external data, you ensure the best performance for your software.

Key takeaway

Treat every piece of external data as "guilty until proven innocent" by verifying its size, type, and range before using it.