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.
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] = '