Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 135 ยท Arrays and Strings

Safe String Handling

Prevent buffer overflows in C - why gets was removed, bounded input with fgets, snprintf with truncation checks, strncpy pitfalls, memccpy and strdup, and lines of any length.

C's string functions trust you completely. strcpy copies until it finds a terminator, scanf("%s") stores a word of any length, and neither asks how big the destination is. When the text is longer than the buffer, they keep writing into whatever memory comes next. That's a buffer overflow, and it has been behind some of the most damaging security holes in computing history, from the 1988 Morris worm to bugs found every year in network software.

The good news is that overflows are preventable with a small set of habits. In this lesson you'll see what actually goes wrong in an overflow, why gets was removed from the language, and how to replace every risky call with a bounded one: fgets for input, snprintf for building strings, careful copying instead of strncpy, and C23's memccpy and strdup. You'll finish by reading lines of any length safely.

What a buffer overflow does

Here's the bug in its simplest form:

C
char name[8];
strcpy(name, "Bartholomew Fitzgerald");   // 23 bytes into an 8-byte array

strcpy writes all 23 bytes. The first 8 land in name; the other 15 overwrite whatever the compiler placed after it: other local variables, saved registers, or the function's return address. Writing past an array is undefined behavior, so anything can happen. In practice you'll see one of these:

  • Corrupted data. A neighboring variable silently changes value.
  • A crash, often far from the buggy line, when corrupted memory is used later.
  • A hijacked program. If an attacker controls the input, they can choose the bytes that overwrite the return address and make the function "return" into code of their choosing.

When the sizes are constants, GCC can catch the mistake at compile time. For the code above it says:

TEXT
warning: '__builtin_memcpy' forming offset [8, 22] is out of the bounds [0, 8] of object 'name' with type 'char[8]' [-Warray-bounds=]

When we ran a similar program on our server, it crashed with a segmentation fault, but that's luck, not a guarantee: other compilers, flags or inputs give other results. And most real overflows involve input, whose length the compiler can't know, so you get no warning at all. The defense has to be in your code.

The rule: every write into a char array must be bounded by the array's size, and you must know what happens when the text doesn't fit (truncate and report, grow the buffer, or reject the input). If a function you're calling can't be told the size, don't use it with data you don't control.

gets is gone: use fgets

gets(buffer) read a line from standard input into buffer, with no way to pass the buffer size. Any line longer than the buffer overflowed it, and nothing the programmer did could prevent that. It was deprecated in C99 and removed in C11. Modern C libraries don't even declare it in C11 or later mode, so our compiler reports:

TEXT
error: implicit declaration of function 'gets'; did you mean 'fgets'? [-Wimplicit-function-declaration]

That suggestion is right. fgets(buffer, size, stream) reads at most size - 1 characters, always adds the terminator, and keeps the newline if the whole line fit. It returns NULL at end of input or on error. The one thing it can't do is make the line fit, so a robust program checks for truncation:

C Bounded input with fgets

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.

The output:

TEXT
got "short line"
got "this line is fa"  (line was too long, cut)
got "ok"

If the buffer contains no newline, either the line was too long or the input ended without a final newline; feof tells the two apart. Discarding the rest of a long line is one policy. A program could also reject the input with an error message, or read the line in pieces into a growing buffer, as the last section of this lesson does. What matters is that you chose a policy, and nothing overflows.

scanf needs the same care: %s and %[...] must always have a width, one less than the buffer size, for example scanf("%15s", word) for char word[16]. Reading Input with scanf and fgets covers the full pattern of reading a line with fgets and then parsing it with sscanf or strtol.

snprintf: the safe way to build strings

sprintf(buffer, format, ...) formats text like printf but writes it into buffer, again with no size limit. Its bounded twin, snprintf(buffer, size, format, ...), is the most useful safety tool in the C library:

  • It never writes more than size bytes.
  • It always terminates the result (when size is at least 1).
  • It returns the number of characters the complete output would have needed (not counting the terminator), or a negative value on an encoding error.

That return value is how you detect truncation: if it's >= size, the output was cut. GCC knows this too; with -Wall it warns about snprintf calls that are likely to truncate and whose return value you ignore, which is a good nudge to always check it.

C snprintf with truncation checks

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.

The output:

TEXT
blue         -> "SKU-00042-blue"
turquoise    -> "SKU-00042-turqu" (truncated)
ultramarine  -> "SKU-00042-ultra" (truncated)
temps: 18 21 19 23 25 22 20 24 26 27
report complete

Change report to char report[24]; and run it again: the loop stops cleanly, the text is cut at 23 characters (temps: 18 21 19 23 25 2), and the program says report was truncated. The used >= sizeof report check before each call matters, because snprintf returns the length it wanted, so used can grow past the buffer size. Computing report + used beyond the end of the array would itself be undefined behavior.

Because snprintf handles numbers, padding and pieces of strings (with %.*s), it can replace most strcpy/strcat chains with a single bounded call: snprintf(path, sizeof path, "%s/%s", directory, file).

The strncpy trap

strncpy(dest, src, n) looks like a bounded strcpy, and it's often recommended as one. It isn't. It was designed for fixed-width fields in old file formats, and it behaves accordingly:

  • If src is shorter than n, it copies it and fills all the remaining bytes of dest with zeros (wasted work on big buffers).
  • If src has n or more characters, it copies exactly n and writes no terminator. The result isn't a string, and the next strlen or printf("%s") reads past the end.

So every strncpy must be followed by manual termination, and it still truncates silently. A small helper is clearer and reports what happened:

C strncpy's missing terminator, and a safe copy

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.

It prints:

TEXT
bytes after strncpy: A B C D E   (no terminator!)
after manual fix: ABCD
Oslo       -> "Oslo"
Wellington -> "Welling" (cut)

GCC also prints a warning above the output, 'strncpy' output truncated copying 5 bytes from a string of length 8 [-Wstringop-truncation], because it can see the constant sizes. Here the truncation is the point of the demo; in real code, treat that warning as a bug report. Notice that city has 8 bytes but holds only 7 letters, "Welling": the helper copies capacity - 1 characters to leave room for the terminator.

You may also meet strlcpy and strlcat, from OpenBSD. They take the full buffer size, always terminate, and return the length they tried to create, like snprintf. They're available on BSD and macOS, in glibc since version 2.38, and in POSIX since 2024, but not in standard C or on older Linux systems like our server. The copy_string helper above gives you the same safety anywhere.

What about strcpy_s and friends? C11's optional Annex K defines "bounds-checking interfaces" such as strcpy_s, strcat_s and gets_s. Microsoft's C library has its own variants, but glibc and most other libraries never implemented Annex K, so code using it isn't portable. Prefer snprintf, fgets and small helpers like copy_string.

C23: memccpy and strdup

C23 standardized two long-time POSIX functions that make safe string code easier.

memccpy(dest, src, c, n) copies bytes from src to dest until it has copied the byte c or n bytes, whichever comes first. If it found c, it returns a pointer to the byte after c in dest; otherwise it returns NULL. Searching for '\0' turns it into a bounded copy that tells you where the string ends, which is exactly what you need to append the next piece without rescanning (the problem with chained strcat calls).

strdup(s) and strndup(s, n) return a new malloc'd copy of a string (or of at most n characters of it). When you don't know how long text is, owning an exact-size heap copy beats guessing a buffer size.

Our server's C library predates C23 and only declares these in POSIX mode, so the example defines a feature-test macro first:

C Concatenating with memccpy, copying with strdup

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.

It prints:

TEXT
roomy: "safe strings need bounds"
tight: "safe string" (truncated)
copy: "Safe strings need bounds", first word: "safe", original: "safe strings need bounds"

The _XOPEN_SOURCE line isn't needed with C libraries that fully support C23. free(NULL) is allowed and does nothing, which is why the error path can free both pointers without checking which one failed.

Reading lines of any length

Fixed buffers always force a choice about long input. When you'd rather accept any length, read in chunks and grow a heap buffer with realloc. POSIX systems provide getline for exactly this; here's a portable version built only on fgets:

C A line reader with no length limit

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.

The output:

TEXT
line 1 (6 chars): Short.
line 2 (126 chars): This line is longer than the 8-byte star...
line 3 (5 chars): Done.

The buffer starts at just 8 bytes and doubles whenever fgets fills it without reaching a newline, so the 126-character line needs only a few reallocations. Note the safe realloc pattern: assign to a temporary pointer first, so that on failure you still hold (and can free) the original block.

A safety checklist

Keep this list next to you when you write string code:

Instead of Use
gets(buf) fgets(buf, sizeof buf, stdin) and check for truncation
scanf("%s", buf) scanf("%15s", buf) (width = size โˆ’ 1), or fgets + sscanf
sprintf(buf, ...) snprintf(buf, sizeof buf, ...) and check the return value
strcpy(dst, src) with unknown length length check first, or a copy_string helper, or snprintf(dst, size, "%s", src)
strncpy(dst, src, n) the same; if you must, terminate by hand afterwards
strcat chains one snprintf, or memccpy tracking the end
guessing a buffer size strdup, or a growing buffer with realloc
printf(user_text) printf("%s", user_text)

And three habits beyond the functions themselves:

  • Pass sizes with buffers. Any function that writes into a char * should also take a size_t capacity, just like fgets and snprintf do.
  • Compile with warnings and test with sanitizers. -Wall -Wextra catches many constant-size mistakes; -fsanitize=address catches overflows at run time during testing. Memory Errors shows how.
  • Decide what happens on overflow. Truncate and report, grow, or reject. Never "it won't happen".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why was gets removed from C in C11?

    gets has no size parameter, so the programmer can't prevent an overflow. fgets takes the buffer size and is the replacement.
  2. 2. char b[10]; int n = snprintf(b, sizeof b, "%s", "hello world"); What are n and b?

    snprintf returns the length the full output needed (11) and writes at most 9 characters plus the terminator. n >= sizeof b tells you it was truncated.
  3. 3. After char t[4]; strncpy(t, "tulip", sizeof t);, what is true?

    When the source has at least n characters, strncpy copies exactly n and adds no '\0'. You must set t[3] = '\0' yourself, or use a safer approach.
  4. 4. What does scanf("%8s", word) need to be safe?

    The width counts characters; scanf then adds a terminator, so 8 characters need 9 bytes.
  5. 5. In the growing line reader, why is realloc's result stored in a temporary pointer first?

    Writing line = realloc(line, ...) would overwrite the only pointer to the old block with NULL on failure, leaking it.

Summary

  • A buffer overflow writes past the end of an array; it's undefined behavior and a classic security hole. The compiler only catches constant-size cases.
  • gets was removed in C11; read lines with fgets, check for a missing newline, and decide what to do with long lines.
  • Give every scanf %s a width of size โˆ’ 1.
  • snprintf is bounded and always terminates; its return value (>= size means truncated) is your truncation check.
  • strncpy may leave no terminator and truncates silently; use a small helper or snprintf instead. strlcpy exists on some systems; Annex K's _s functions are rarely available.
  • C23 adds memccpy for bounded copying that reports where the string ends, and strdup/strndup for exact-size heap copies (older libraries need _POSIX_C_SOURCE or _XOPEN_SOURCE).
  • For input of any length, grow a heap buffer with realloc, using a temporary pointer.

Next: Converting Strings and Numbers, where you'll turn text into numbers safely and back again.