snprintf(), strncpy() and strlcpy()

snprintf() is used to Write formatted output to a character array, up to a given maximum number of characters.

strncpy() is to copy a string, to a maximum length.

Although both allow a programmer to select a number, e, g. n, as the maximum, there are some differences.

snprintf() copies at most n – 1 characters into the output buffer and then appends a terminating null character ( a character with all its bits set to zero). Therefore, the string in the output buffer is appropriated terminated.

strncpy() copies no more than n characters into destination string, and it doesn’t guarantee the termination of the destination string. Details are as below:

– If the source string  is shorter than n characters, null characters are appended to the destination string, until n characters have been written. – If the source string is longer than n characters, then n characters will be copied to the destination string.

With this in mind, it’s better to terminate the string explicitly:

        strncpy (buffer, name, sizeof (buffer));

        buffer[sizeof (buffer) – 1] = ‘\0’;

if the buffer was allocated using calloc(), or has been initialized to all 0, an alternative is:

   strncpy (buffer, name, sizeof (buffer) – 1);

An alternate is to use strlcpy() which is a safer replacement for strncpy(). strlcpy() copies up to (n-1) characters to the dst and NUL-terminate the result.

One note is thtat strncpy() and strlcpy() return different types: strncpy() returns a pointer which points to the dst; strlcpy() returns the length of the source string.