Date: 2007oct16
Update: 2026sep14
Language: C/C++
Keywords: LPCSTR, LPSTR, LPTSTR, LPCTSTR
Q. C/C++: strlcpy Copy a strings ensuring no buffer overflows and a terminating NUL
A. If you don't have one builtin, use this:
#include <stddef.h>
#include <string.h>
#include <stdio.h>
size_t strlcpy(char *dst, const char *src, const size_t bufsize) {
size_t len;
if (src == NULL) return 0;
len = strlen(src);
if (dst == NULL) return len;
if (len >= bufsize) len = bufsize - 1;
memcpy(dst, src, len * sizeof(char));
dst[len] = '\0';
return len;
}
Example Use:
void main() {
{ // With a larger buffer
char buf[100];
strlcpy(buf, "one two three four", sizeof(buf));
printf(" larger buf=%s\n", buf);
}
{ // With a smaller buffer
char buf[10];
strlcpy(buf, "one two three four", sizeof(buf));
printf("smaller buf=%s\n", buf);
}
}
Output:
larger buf=one two three four
smaller buf=one two t