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);
while (*dst && size > 0) // added @JS1 edit
{
dst++;
len++;
size--;
}
while (*src && size-- > 1) //added @JS1 edit
*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
manpage on the internet and quoted the most important parts here. It seems likestrlcatkeeps up to the firstlcharacters from the combined destination and source strings. There are oddities here that may or may not be intended. \$\endgroup\$