The snprintf() Function

The snprintf() Function

The C99 standard defines a new version of the function sprintf(), namely snprintf(), with the following prototype:

   int snprintf(char * restrict s, size_t n,                    const char * restrict format, ...);

The additional argument n (highlighted) contains the maximal number of characters that the snprintf() copies to the buffer s. If the source buffer contains more characters than n, only n-1 characters are written to s and a null is appended at the end. Note that unlike sprintf(), which stops copying characters to s only after it has reached a null character, snprintf() might copy only a portion of the source string to s if n isn’t larger than the number of characters in the source buffer. In other words, to copy the source buffer to s completely, n must be larger than the source’s size. The argument n ensures that snprintf() doesn’t cause a buffer overflow by writing past the end of s.


Share the Post: