Ulrich's criticism is based on the idea that a string truncation that is not detected by the program can lead to security issues, through incorrect logic. Therefore, to be secure, you need to check for truncation. To do this for a string concatenation means that you are doing a check along the lines of this:
if (destlen + sourcelen > dest_maxlen)
{
/* Bug out */
}
Now, strlcat
does effectively do this check, if the programmer remembers to check the result - so you can use it safely:
if (strlcat(dest, source, dest_bufferlen) >= dest_bufferlen)
{
/* Bug out */
}
Ulrich's point is that since you have to have destlen
and sourcelen
around (or recalculate them, which is what strlcat
effectively does), you might as well just use the more efficient memcpy
anyway:
if (destlen + sourcelen > dest_maxlen)
{
goto error_out;
}
memcpy(dest + destlen, source, sourcelen + 1);
destlen += sourcelen;
(In the above code, dest_maxlen
is the maximum length of the string that can be stored in dest
- one less than the size of the dest
buffer. dest_bufferlen
is the full size of the dest buffer
).