What is a buffer overflow at a memory-safety level, and what classic mistake causes one in C?
A program writes past (or reads past) the end of a memory region — corrupting adjacent data or leaking it.
In C/C++ this happens when you trust input size assumptions. The textbook example:
#define BUFSIZE 128
char *copy_string(const char *s) {
char *buf = malloc(BUFSIZE); // assumes input ≤ 127 bytes
if (buf) strcpy(buf, s); // heap overflow if strlen(s) > 127
return buf;
}
strcpy copies until it hits a NUL — there is no length check. Give it a 200-byte string and it writes 72 bytes past the end of the heap allocation, corrupting whatever malloc placed next. On the stack, the equivalent (strcpy into a fixed-size local) lets attackers overwrite the saved return address and divert execution.
Why this still matters in 2024:
- A huge fraction of CVEs (Microsoft has said ~70%) are memory-safety bugs.
- Heartbleed (CVE-2014-0160) was a read overflow in OpenSSL — the server believed the client's length field and returned up to 64 KB of arbitrary memory.
Defenses:
- Use memory-safe languages (Rust, Go, Java, C#) — the whole class of bug disappears.
- In C/C++: prefer bounded variants (
strncpy,snprintf), enable-fstack-protector, ASLR, NX/DEP, run AddressSanitizer in CI. - Validate input length before trusting it as a buffer size.
Tip: The mental model is "I told the program data is 4 bytes — it believes me — so it reads 4 bytes from a buffer that only holds 1." Heartbleed in one sentence.