strlen() / strcpy() / strncpy()
These are fundamental functions for getting the length of a string or copying it into another buffer. Writing beyond the buffer size is a serious security vulnerability, so you must handle boundaries with great care.
Syntax
// Returns the length of a string in bytes, excluding the null terminator. size_t strlen(const char *s); // Copies the contents of src into dst, including the null terminator. // The memory regions of dst and src must not overlap. char *strcpy(char *dst, const char *src); // Copies up to n bytes from src into dst. // If src is shorter than n bytes, the remainder is padded with null characters. // If src is n bytes or longer, no null terminator is appended (use with caution). char *strncpy(char *dst, const char *src, size_t n);
Function Comparison
| Function | Buffer Protection | Null Termination Guaranteed | Use Case |
|---|---|---|---|
| strcpy() | No | Yes | Only safe when you can guarantee dst is large enough. |
| strncpy() | Yes (size-limited) | No (not guaranteed even within n) | Limits the number of bytes copied, but you must manually append a null terminator. |
| strlcpy()* | Yes (size-limited) | Yes | BSD extension. Always guarantees null termination — a safer alternative (not standard C). |
| snprintf() | Yes (size-limited) | Yes | Always guarantees null termination. Can also be used for copying. |
Sample Code
#include <stdio.h>
#include <string.h>
int main(void) {
const char *src = "Hello, C!";
// Get the length of the string with strlen (null terminator not counted).
printf("Length: %zu\n", strlen(src)); // Outputs: Length: 9
// Copy with strcpy (assumes dst is large enough).
char dst1[32];
strcpy(dst1, src);
printf("strcpy: %s\n", dst1); // Outputs: strcpy: Hello, C!
// Copy with strncpy, limiting the number of bytes.
char dst2[6];
strncpy(dst2, src, sizeof(dst2) - 1); // Pass sizeof - 1 as n.
dst2[sizeof(dst2) - 1] = '\0'; // Manually ensure null termination.
printf("strncpy(5): %s\n", dst2); // Outputs: strncpy(5): Hello
// snprintf can be used as a safe copy that handles null termination automatically.
char dst3[8];
snprintf(dst3, sizeof(dst3), "%s", src);
printf("snprintf: %s\n", dst3); // Outputs: snprintf: Hello, (7 chars + '\0')
return 0;
}
Notes
strcpy() does not check the size of the destination buffer at all. If src is longer than dst, a buffer overflow occurs, corrupting adjacent memory and creating a security vulnerability. In modern code, using snprintf() is recommended instead.
strncpy() does not append a null terminator when src does not fit within n characters. Always manually set the last byte to null (dst[n-1] = '\0'), or use snprintf() as an alternative.
For string concatenation, see strcat() / strncat(). For comparison, see strcmp().
If you find any errors or copyright issues, please contact us.