I have to implement my own version of the strlcat() function from the standard C library.
size_t strlcat(char * restrict dst, const char * restrict src, size_t size);
I have two questions about how it works :
Does it NUL_terminates dst in every case?
In my man I have the following :
strlcat() take the full size of the buffer (not just the length) and guarantee to NUL-terminate the result (as long as size is larger than 0 or, in the case of strlcat(), as long as ther is at least one byte free in dst).
and :
The strlcat() function appends the NUL-terminated string src to the end of dst. It will append at most size - strlen(dst) - 1 bytes, NUL-terminating the result.
but also :
Note however, that if strlcat() traverses size characters without finding a NUL, the length of the string is considered to be size and the destination string will not be NUL-terminated (since there was no space for the NUL).
So, should I NUL_terminate dst in EVERY case?
On one hand it says there is a case where the dst string isn't NUL_terminated.
On the other hand the man says that strlcat() guarantees that dst will be NUL_terminated, and wouldn't a non NUL_terminated string be pretty insecure?
Could someone give me an example where this case would occur?
What does the returned value represents and why is there this behavior?
Here are the results I get with some tests :
Before : || After :
dst | src | size || dst | return
------------------------||--------------------
dst\0 | src\0 | 0 || dst\0 | 3
dst\0 | src\0 | 1 || dst\0 | 4
dst\0 | src\0 | 2 || dst\0 | 5
dst\0 | src\0 | 3 || dst\0 | 6
dst\0 | src\0 | 4 || dst\0 | 6
dst\0 | src\0 | 5 || dsts\0 | 6
dst\0 | src\0 | 6 || dstsr\0 | 6
dst\0 | src\0 | 7 || dstsrc\0 | 6
dst\0 | src\0 | 8 || dstsrc\0 | 6
From the man again :
[The strlcat() function] return the total length of the string [it tries] to create. For strlcat() that means the initial length of dst plus the length of src.
dst's and src's sizes are constant in my tests (3 and 3).
So why are there cases where the returned value is different from 6?
Isn't it rather (len(dst) + min(size, len(src))?
What does size represents?
The strlcat() function appends the NUL-terminated string src to the end of dst. It will append at most size - strlen(dst) - 1 bytes, NUL-terminating the result.
So size should be the the length ('\0' char included) dst is allowed to be at the end? Is that right?
strlcatis not in Standard Cman strlcatI have this in "library section" : Standard C Library (libc, -lc)