C Reference ยท string.h
Safe string handling in C
How to copy and join C strings without buffer overflows: snprintf, bounded copies, checking truncation, strlcpy availability and the strncpy trap.
Most string bugs in C come from one fact: the library functions do not know how big your destination buffer is. strcpy and strcat write until the source ends, wherever that is. Safe string handling means always passing the buffer size to the function that writes, and always checking whether the result was cut short.
This page collects the patterns that work with the standard library alone. The standard does not include strlcpy or strlcat (they come from BSD, and glibc added them only in version 2.38), so portable code uses snprintf or a short helper of its own.
char name[16]; int n = snprintf(name, sizeof name, "%s-%d", prefix, id); if (n < 0 || (size_t)n >= sizeof name) { /* error or truncated */ }
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.
Syntax
This is a concept page, so there is no single declaration. The functions involved are:
int snprintf(char *restrict s, size_t n, const char *restrict format, ...); char *strncpy(char *restrict dst, const char *restrict src, size_t n); char *strncat(char *restrict dst, const char *restrict src, size_t n); void *memcpy(void *restrict dst, const void *restrict src, size_t n); size_t strlcpy(char *dst, const char *src, size_t size); /* BSD, glibc 2.38+, not ISO C */ size_t strlcat(char *dst, const char *src, size_t size); /* BSD, glibc 2.38+, not ISO C */
| Function | Terminates the result? | Detects truncation? | Notes |
|---|---|---|---|
snprintf |
Yes, when n > 0 |
Yes, from the return value | Standard since C99. Best general choice. |
strncpy |
Not always | No | Pads with zeros up to n; made for fixed-width fields, not for safe copying. |
strncat |
Yes | Not directly | n is the maximum number of characters to append, not the buffer size. |
strlcpy, strlcat |
Yes | Yes, from the return value | Not in ISO C or on the course runner (glibc 2.28). |
Usage notes
- Pass
sizeof buffer, not a guess. This only works where the array itself is in scope. A buffer passed to a function has decayed to a pointer, sosizeofgives the pointer size; pass the capacity as a separate parameter. - Read the return value of
snprintf. It returns the number of characters that would have been written, excluding the terminator. A value>= nmeans truncation; a negative value means an encoding error. strncpyis not a saferstrcpy. Ifsrcis as long asnor longer, no null terminator is written. Ifsrcis shorter, it writes zeros all the way up ton, which costs time on big buffers. Use it for fixed-width, zero-padded records only.strncatlimit. Its third argument counts characters to append, so the correct bound issizeof dst - strlen(dst) - 1. Mistakes here are a classic overflow.- Check before you copy when a failure should be handled: compare
strlen(src)with the capacity, and return an error instead of silently cutting the data. - Truncation is a bug too. Cutting a file path or SQL statement short can change its meaning. Decide for each buffer whether truncation is acceptable.
- Do not use
gets. It was removed in C11 because no size can be given. Usefgetswith the buffer size. - Format strings. Never pass user data as the format of
printforsnprintf; use"%s"and pass the data as an argument. - Dynamic allocation avoids fixed limits: measure with
snprintf(NULL, 0, ...), thenmalloc(needed + 1)and format again. - Tools. Compile with
-Wall -Wextra -Wformat-truncation, and test with AddressSanitizer to catch overflows that slip through.