Skip to content
Tutorials Center
My learning

Topics

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.

C
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, and scanf("%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 int length converted to a huge size_t, or count * size wrapping around before malloc.

Try it

C Bounded copying with snprintf

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.

C Reading a line of any length safely

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_t parameter or use a struct with a pointer and a length.
  • sizeof on an array parameter is wrong. In void f(char buf[64]), buf is a pointer, so sizeof buf is the pointer size.
  • Leave room for the NUL. A string of n characters needs n + 1 bytes.
  • 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 -Wextra and 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 _s functions exist but are not available everywhere. See strlcpy and Bounds-checked functions.