3 ms·
> In particular, they put 0…N NUL bytes at the end, but you usually want exactly one NUL byte, no more, no less. strncpy() does that but strncat() does not. s
by __david__ 11y ago
> In particular, they put 0…N NUL bytes at the end, but you usually want exactly one NUL byte, no more, no less.
strncpy() does that but strncat() does not.
strncat(s1,s2,size) is usually wrong for a different reason: the size argument specifies how many bytes to copy from s2 to the end of s1 (not including the trailing NULL). This means to not buffer overflow your s1 you need to call it like this
strncat(s1, s2, sizeof(s1) - strlen(s1) - 1);
...Which of course everyone forgets. strlcat() is a nice replacement because it does that calculation for you, so you can just do:
strlcat(s1, s2, sizeof(s1));
and you won't buffer overflow your s1.
- jandrese 11y agoOf course strl... functions are still braindamaged because they still return the length of the original string, regardless of what parameter you specified in the third argument. So if the initial string has lost its null terminator the strl... functions will still core dump even if you specified an otherwise safe size. Also, if you're copying the first few bytes out of an enormous buffer (especially a file mmap) it can take a long time for the function to chew through the rest of the buffer calculating that return value that you don't even care about. That's why it's usually better to just use memcpy or memmove instead.
- dietrichepp 11y agoIn particular, most people end up using memcpy/memmove, snprintf, or a library like strbuf. The BSD devs are somewhat unusual for favoring strlcpy.