cstringstrlcpy

Problem with my own implementation of strlcpy()?


I just faced a problem when testing an implementation of strlcpy()

long unsigned int ft_strlcpy(char *dst, const char *src, unsigned int len)
{
    unsigned int l;
    unsigned int i;

    i = 0;
    while (i < len - 1)
    {
        if (*src != '\0')
            *dst++ = *src++;
        i++;
    }
    *dst = '\0';
    return i + 1;
}

I did a test with the original strlcpy() but I didn't get the same result.

src = "string", len = 6

Output of my strlcpy():

return value = 6
dst = strin

Output of the original strlcpy():

return value = 10
dst = strin

The result is the same in dst but the return value should be the length of the string it's trying to make.


Solution

  • From the documentation

    The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that means the length of src.

    You're returning the length of the resulting string, not the length it would have been without the len limit.

    Save strlen(src) in a variable and return that at the end.

    size_t ft_strlcpy(char *dst, const char *src, size_t len)
    {
      size_t l = strlen(src);
      size_t i = 0;
    
      while (i < len - 1 && *src != '\0')
      {
          *dst++ = *src++;
          i++;
      }
      *dst = '\0';
      return l;
    }
    

    Also, the len parameter and the return type should be size_t.