Course contentsShow
← C
Lesson 431 of 1,2196. Arrays and StringsFree lesson

The danger of Buffer Overflow

The danger of Buffer Overflow

What you'll learn: How writing data beyond the boundaries of an array can lead to unpredictable crashes and security vulnerabilities.

The "Overflow" Analogy

Imagine you have a row of ten lockers in a hallway. You are assigned Locker #5. If you try to stuff so much gear into your locker that it physically bursts through the metal walls, you will end up damaging Locker #4 and Locker #6.

In C, an array is a fixed row of "lockers" in your computer's memory. A buffer overflow happens when you try to put more data into an array than it was designed to hold. Because C trusts the programmer to manage boundaries, it won't always stop you from "bursting the walls." Instead, it will simply overwrite whatever happens to be sitting next to that array in memory.

Why it happens

In many modern languages, the computer checks every time you access a list to make sure you aren't going out of bounds. C does not do this automatically. If you have an array of size 5 but tell the computer to write to the 10th index, C will calculate exactly where that 10th spot would be and overwrite the data sitting there—even if that memory belongs to another variable or a critical piece of the program's instructions.

#include <stdio.h>
#include <string.h>

int main() {
    int cookie_jar_locked = 1; // 1 means true
    char password[8];

    // DANGER: We are putting 12 characters into an 8-character space.
    // The extra characters "overflow" and can overwrite 'cookie_jar_locked'.
    strcpy(password, "SUPERSECRET123"); 

    printf("Password stored: %s\n", password);
    printf("Is jar locked? %d\n", cookie_jar_locked); 

    return 0;
}

The Consequences

When you overflow a buffer, three things usually happen:

  1. Corruption: You accidentally change the value of other variables (like the cookie_jar_locked flag above).
  2. Crashes: The program tries to read corrupted memory, gets confused, and shuts down (a "Segmentation Fault").
  3. Security Risks: Hackers can intentionally trigger overflows to overwrite a program's return address, forcing the computer to run malicious code instead of the original program.

Key takeaway

A buffer overflow occurs when you write past the end of an array, corrupting adjacent memory and creating serious security flaws.