Although you can just use another strlcpy function, as another message recommends, or use snprintf(dest, len, "%s", src) (which always completes the buffer), this is what I noticed when looking at your code:
size_t s_strlcpy(char *dest, const char *src, const size_t len) { size_t i = 0;
It is not necessary to create len const here, but it can be useful as it checks that you are not modifying it.
for(i = 0; i < len - 1; i++) {
Unfortunately. What if len 0? size_t usually unsigned, so (size_t) 0 - 1 will become something like 4294967295 , causing your routine to move through your program memory and break into an unprinted page.
if(*src != '\0') { *dest++ = *src++; } else { break; } } *dest = '\0';
The above code looks good to me.
return i; }
According to Wikipedia , strlcpy returns strlen(src) (actual string length), and not the number of bytes copied. Therefore, you need to continue counting characters in src until you hit '\0' , even if it exceeds len .
Also, if your for loop ends in len - 1 , your function will return len-1 , not len, as you expected.
When I write such functions, I usually prefer to use the start pointer (call it S) and the end pointer (call it E). S indicates the first character, and E indicates one character after the last character (which makes it such that E - S is the length of the string). Although this technique may seem ugly and obscure, I found it pretty reliable.
Here is the above version of how I will write strlcpy:
size_t s_strlcpy(char *dest, const char *src, size_t len) { char *d = dest; char *e = dest + len; const char *s = src; while (*s != '\0' && d < e) *d++ = *s++; if (d < e)