Buffer Overflow
A buffer overflow is a write (or a read) past the end of an array or a malloc block. C does not check bounds. The extra bytes are other variables, saved registers, or heap metadata.
Detailed Explanation
char buf[8]; strcpy(buf, "too long!!"); writes past buf and clobbers whatever the compiler placed next. On the stack that has historically been the return address, which is why overflow is a remote-code-execution primitive. On the heap it is the next chunk's size field. Modern mitigations (stack canaries, ASLR, non-executable stack, fortified strcpy) raise the bar. They do not make an overflow defined.
Overflows come from unbounded copies (strcpy, sprintf, gets — gets is removed), from a length you trusted (memcpy(dest, src, n) with n > dest_sz), from an unsigned wrap (n + 1 becomes 0), and from off-by-one that forgets the terminator.
The fix is a capacity in every API that writes. snprintf(dest, dest_sz, ...). memcpy only after n <= dest_sz. fgets(buf, sizeof buf, fp). Functions you write take dest and dest_sz. Functions that cannot take a size — because they are a bad old API — you do not call.
Reads past the end are overflows too (over-reads). Heartbleed was an over-read. strlen on a non-terminated buffer is an over-read. They leak memory and they can crash.
Tools: -fsanitize=address, -D_FORTIFY_SOURCE=2, Valgrind, fuzzers. They find the write. They do not invent a bounds check in production unless you ship the sanitizer, which you usually do not. The check belongs in your code.
Code Examples
#include <stdio.h>
#include <string.h>
int main(void)
{
char dest[8];
const char *src = "hello";
if (strlen(src) + 1 > sizeof dest) {
return 1;
}
memcpy(dest, src, strlen(src) + 1);
printf("%s\n", dest); /* prints: hello */
return 0;
}#include <stdio.h>
int main(void)
{
char dest[8];
int n = snprintf(dest, sizeof dest, "%s", "overflowing");
printf("%s %d\n", dest, n);
/* dest is "overflo"; n is 11, the untruncated length */
return 0;
}Common Gotchas
`gets` and unbounded `strcpy`/`sprintf` are defects
the destination size is not in the call.
A stack canary crash is an overflow you are lucky to see
the bug was the write, not the canary.
`strncpy` is not a safe `strcpy`
it may omit the terminator, which turns the next `%s` into an over-read.
An unsigned length wrap (`need = n + 1` when `n == SIZE_MAX`) allocates nothing
An unsigned length wrap (`need = n + 1` when `n == SIZE_MAX`) allocates nothing and then copies `n` bytes