devxlogo

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.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist