The following code seems to be working fine (updated!):
size_t ft_strlcat(char *dst, const char *src, size_t size)
{
size_t len;
size_t slen;
len = 0;
slen = strlen(src); //replaced dst with src correct return value
while (*dst && size > 0 && size--)
// added @JS1 edit
{
dst++;
len++;
}size--;
}
while (*src && size-- > 1 && size--) // size > 1 for leaving 1 extra space toadded write@JS1 NULLedit
*dst++ = *src++;
if (size == 1 || *src == 0)
// **VERY IMPORTANT:** read update below
*dst = '\0';
return (slen + len);
}
I also renamed the variables as suggested. I tried to implement memcpy but that needs 2 extra variables and an other strlen call.
Tests:
My function
./a.out abc efgh 0
Concatenated string:abc Return value:4
./a.out abc efgh 5
Concatenated string:abce Return value:7
./a.out abc efgh 7
Concatenated string:abcefg Return value:7
./a.out abc efgh 8
Concatenated string:abcefgh Return value:7
./a.out abc efgh 9
Concatenated string:abcefgh Return value:7
Bsd function:
/a.out abc efgh 0
Concatenated string:abc Return value:4
./a.out abc efgh 5
Concatenated string:abce Return value:7
/a.out abc efgh 7
Concatenated string:abcefg Return value:7
./a.out abc efgh 8
Concatenated string:abcefgh Return value:7
./a.out abc efgh 9
Concatenated string:abcefgh Return value:7
It seems right now, please if you have any other suggestions or more simple methods post it.
Update:
After running tests this with big sizes: ./a.out abc efgh 102910 | cat -e
the output was strange:
Concatenated string:abcefghM-^? $
Return value:7 $
This was fixed by forcing the Terminator char by adding the condition *src == 0 to the if statement