strncpy vs. strncat
However, strncpy and strncat etc. add a null limiter if there is room.
Actually strncpy and strncat very different:
strncpy writes a "NUL-filled string of n-bytes" to the n-byte buffer: a string of length l no more than n, so the last nl bytes are filled with NUL. Pay attention to the plural: all last bytes are nullified, mark only one. Also note that the maximum allowable value for l is indeed n, so there may be null NUL bytes: the buffer cannot contain a null-terminated string. (GCC has an unbearable function for measuring such a "NUL-filled n-byte string": strnlen .)
Conversely, strncat outputs a string with a null character to the buffer. In both cases, the string is truncated if it is too long, but in the case of strncpy string of letters will fit into the n-byte buffer, whereas in the case of strncat result of n letters will only fit into the (n + 1) -byte buffer.
This difference causes a lot of confusion for beginners and not even beginners. I even saw a lesson and books that teach "safe C programming" that confused and contradicted the information about these standard features.
These so-called โsafeโ C string management functions (โ strn* โ) have been heavily criticized in the โsafe programmingโ C community, and more developed (but non-standard) alternatives have been invented (in particular, the โ strl* โ family: strlcpy . ..).
Summary:
strncpy will add a null terminator if there is room ;strncat will always add a null terminator.
curiousguy
source share