Home > Back-end >  problem on My own implemntation of strlcpy?
problem on My own implemntation of strlcpy?

Time:11-05

Hello 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 in the return value should be the length of the string trying to make

CodePudding user response:

It should return the length of the string to copy, not the length of the result.


You seem to be claiming you did

ft_strlcpy(dst, "string", 6);  // 6

and

strlcpy(dst, "string", 6);  // 10

But the output suggests you did something closer to

ft_strlcpy(dst, "abcdefghij", 6);  // 6

and

strlcpy(dst, "abcdefghij", 6);  // 10

strlcpy returns the length of the string it tried to create, meaning the length of the string that would have been copied if the limit hadn't been imposed. This is not what ft_strlcpy returns.


Fixed:

size_t ft_strlcpy(char *dst, const char *src, size_t len) {
  if ( !len )
     return strlen(dst);

  size_t i = 0;
  while ( --len ) {
     if ( !( *dst   = *src   ) )
        return i;

       i;
  }

  while (*str) {
       str;
       i;
  }

  return i;
}

CodePudding user response:

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.

  • Related