Skip to main content

Lesson 5 of 7

Buffer Overflow - The Classic C Vulnerability

A buffer overflow occurs when a program writes data beyond the end of an allocated buffer. In C, this overwrites adjacent memory - which may be another variable, a saved return address (enabling code injection), or heap metadata. Buffer overflows are responsible for some of the most famous security exploits in history. Understanding how they work is essential for writing safe C.

11 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Buffer Overflow - What Gets Overwritten & How to Prevent It

Buffer Overflow - What Gets Overwritten & How to Prevent It
#include <stdio.h>
#include <string.h>

/* ── Stack layout during a function call ─────────────────────
   High addresses
   ┌─────────────────────────────┐
   │  saved return address       │  ← overwriting this = arbitrary code exec
   ├─────────────────────────────┤
   │  saved base pointer (rbp)   │
   ├─────────────────────────────┤
   │  local variable: auth=0     │ ← overwriting this = privilege escalation
   ├─────────────────────────────┤
   │  char buf[16]               │ ← writes start here
   └─────────────────────────────┘
   Low addresses                                                 */

/* DANGEROUS function - classic stack overflow */
void dangerous_login(void) {
    char buf[16];
    int authenticated = 0;   /* sits ABOVE buf on the stack */

    printf("Password: ");
    /* gets(buf); NEVER USE gets - removed in C11 */
    /* scanf("%s", buf); - also unsafe: no length limit */

    /* If user enters 17+ characters, 'authenticated' is overwritten!
       A crafted input like "AAAAAAAAAAAAAAAA"
       would set authenticated = 1 without checking the password.  */

    if (authenticated) {
        printf("Access granted!
");
    } else {
        printf("Access denied
");
    }
}

/* SAFE version - always use length-limited reads */
void safe_login(void) {
    char buf[16];
    int authenticated = 0;

    printf("Password: ");
    if (fgets(buf, sizeof(buf), stdin) == NULL) return;
    /* fgets reads at most sizeof(buf)-1 = 15 chars + null terminator  */
    /* buf[strlen(buf)-1] might be '
' - trim it: */
    size_t len = strlen(buf);
    if (len > 0 && buf[len-1] == '
') buf[len-1] = '';

    if (strcmp(buf, "secret123") == 0) authenticated = 1;

    if (authenticated) printf("Access granted!
");
    else               printf("Access denied
");
}

/* ── Heap overflow ───────────────────────────────────────── */
/* char *p = malloc(10);
   strcpy(p, "this string is way longer than 10 bytes");
   ↑ overwrites heap metadata, corrupts other allocations    */

/* ── Prevention strategies ───────────────────────────────── */
/* 1. Always use length-limited functions: fgets, strncpy, snprintf
   2. Validate input length before writing
   3. Compile with: -fstack-protector-strong (adds stack canary)
   4. Run with: -fsanitize=address (ASAN) to detect overflows
   5. Use valgrind for heap overflow detection                  */

int main(void) {
    /* Demonstrate snprintf - safe sprintf alternative */
    char out[32];
    int n = snprintf(out, sizeof(out), "Hello, %s! You are %d.", "Alice", 30);
    printf("snprintf wrote %d chars: %s
", n, out);
    /* snprintf ALWAYS null-terminates and returns chars that would
       have been written (> sizeof-1 means truncation occurred)  */
    if (n >= (int)sizeof(out)) printf("WARNING: output was truncated!
");

    return 0;
}

Common Mistakes

  • `scanf("%s", buf)` without a width limit - reads until whitespace, no bounds check. On a 16-byte buffer, 100-char input overflows onto the stack. Always: `scanf("%15s", buf)` where 15 = buffer size - 1.
  • Using `sprintf` instead of `snprintf` - `sprintf(buf, fmt, ...)` has no length limit. `snprintf(buf, sizeof(buf), fmt, ...)` truncates and always null-terminates.
  • Off-by-one in the limit - `strncpy(dst, src, sizeof(dst))` leaves no room for the null terminator when the source is exactly `sizeof(dst)` characters. Always pass `sizeof(dst) - 1`.

Tip

Tip

Practice Buffer Overflow The Classic C Vulnerability in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Unchecked buffer writes can overwrite return addresses, compromising memory safety

Practice Task

Note

Practice Task - (1) Write a working example of Buffer Overflow The Classic C Vulnerability from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Buffer Overflow The Classic C Vulnerability is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • A buffer overflow occurs when a program writes data beyond the end of an allocated buffer.
  • `scanf("%s", buf)` without a width limit - reads until whitespace, no bounds check. On a 16-byte buffer, 100-char input overflows onto the stack. Always: `scanf("%15s", buf)` where 15 = buffer size - 1.
  • Using `sprintf` instead of `snprintf` - `sprintf(buf, fmt, ...)` has no length limit. `snprintf(buf, sizeof(buf), fmt, ...)` truncates and always null-terminates.
  • Off-by-one in the limit - `strncpy(dst, src, sizeof(dst))` leaves no room for the null terminator when the source is exactly `sizeof(dst)` characters. Always pass `sizeof(dst) - 1`.

Topics in This Module

0/7 done