gcc 4.4.4 c89
My program does a lot of string coping. I don’t want to use the strncpy as it doesn’t nul terminate. And I can’t use strlcpy as its not portable.
Just a few questions. How can I put my function through its paces to ensure that it is completely safe and stable. Unit testing?
Is this good enough for production?
size_t s_strlcpy(char *dest, const char *src, const size_t len)
{
size_t i = 0;
/* Always copy 1 less then the destination to make room for the nul */
for(i = 0; i < len - 1; i++)
{
/* only copy up to the first nul is reached */
if(*src != '\0') {
*dest++ = *src++;
}
else {
break;
}
}
/* nul terminate the string */
*dest = '\0';
/* Return the number of bytes copied */
return i;
}
Many thanks for any suggestions,
Although you could simply use another strlcpy function as another post recommends, or use
snprintf(dest, len, "%s", src)(which always terminates the buffer), here are the things I noticed looking at your code:No need to make
lenconst here, but it can be helpful since it checks to make sure you didn’t modify it.Oops. What if len is 0?
size_tis usually unsigned, so (size_t)0 – 1 will end up becoming something like4294967295, causing your routine to careen through your program’s memory and crash into an unmapped page.The above code looks fine to me.
According to Wikipedia,
strlcpyreturnsstrlen(src)(the actual length of the string), not the number of bytes copied. Hence, you need to keep counting the characters insrcuntil you hit'\0', even if it exceedslen.Also, if your for loop terminates on the
len - 1condition, your function will returnlen-1, not len like you’d expect it to.When I write functions like this, I usually prefer to use a start pointer (call it S) and end pointer (call it E). S points to the first character, while E points to one character after the last character (which makes it so E – S is the length of the string). Although this technique may seem ugly and obscure, I’ve found it to be fairly robust.
Here’s an over-commented version of how I would write strlcpy: