C Reference ยท Concepts and Tools
Buffer overflows in C
Understand buffer overflows in C: how writing past an array corrupts memory, the unsafe functions behind them, and bounded alternatives such as snprintf and fgets.
A buffer overflow happens when a program writes (or reads) past the end of an array or allocated block. C does not check array bounds, so the write lands in whatever sits next to the buffer: another variable, a saved return address, heap bookkeeping. The result ranges from a silent wrong answer to a crash to full control of the program by an attacker, which is why overflows have been behind a large share of serious security vulnerabilities for decades.
A bounds error is always undefined behavior. It does not matter whether the buffer is on the stack, on the heap or in a global: once you step outside the object, the standard promises nothing. Preventing overflows is mostly a matter of discipline: always know the size of the destination, and use operations that take that size.
How an overflow happens
The following code is read-only; it is the textbook mistake and its behavior is not reliable.
char name[8]; strcpy(name, user_text); /* copies until the NUL: any length fits... or not */ gets(line); /* removed in C11: cannot be used safely */ sprintf(path, "%s/%s", dir, file); /* no size limit on the result */ int values[4]; for (int i = 0; i <= 4; i++) { /* off by one: writes values[4] */ values[i] = i; }
The common causes are:
- Unbounded string functions:
strcpy,strcat,sprintf,gets, andscanf("%s")with no width. - Off-by-one errors: forgetting the room for the terminating
'\0', or using<=where<is needed. - Wrong sizes:
sizeof(pointer)where the array size was meant, or multiplying a count without checking for overflow. - Trusting lengths from outside: a length field in a file or network packet that is larger than the buffer.
- Integer problems: a negative
intlength converted to a hugesize_t, orcount * sizewrapping around beforemalloc.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Prevention checklist
| Instead of | Use |
|---|---|
gets(buf) |
fgets(buf, sizeof buf, stdin) |
strcpy(dst, src) |
snprintf(dst, sizeof dst, "%s", src), or check strlen(src) < sizeof dst and memcpy |
strcat(dst, src) |
track the current length and use snprintf or memcpy with a checked size |
sprintf(buf, ...) |
snprintf(buf, sizeof buf, ...) |
scanf("%s", buf) |
scanf("%15s", buf) (width = size - 1), or fgets + sscanf |
malloc(n * size) |
check for overflow first, or use calloc(n, size), which checks for you |
strncpy as a "safe" copy |
it does not always add the NUL and zero-pads the rest; prefer the options above |
Usage notes
- Pass the buffer size around. A pointer parameter forgets the array length; add a
size_tparameter or use astructwith a pointer and a length. sizeofon an array parameter is wrong. Invoid f(char buf[64]),bufis a pointer, sosizeof bufis the pointer size.- Leave room for the NUL. A string of
ncharacters needsn + 1bytes. - Reads count too. Reading beyond a buffer (an over-read) can leak secrets, as in the Heartbleed bug.
- Compile with protection.
-fstack-protector-strong,-D_FORTIFY_SOURCE=2(with optimization),-Wall -Wextraand Position Independent Executables make exploits harder, but they do not fix the bug. - Test with tools. AddressSanitizer reports the exact line of most overflows. See Sanitizers and Valgrind.
strlcpy(BSD, glibc 2.38) and the optional Annex K_sfunctions exist but are not available everywhere. See strlcpy and Bounds-checked functions.
Related
- Secure coding in C and Undefined behavior catalog
- snprintf and sprintf, fgets and strcpy
- Memory errors
- Tutorial: String safety and Memory errors