Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

snprintf — formatting with a buffer limit

snprintf writes formatted text into a buffer with a specified capacity. Its return value detects truncation; the capacity includes the terminating null character.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdio.h>
int snprintf(char * restrict s, size_t n, const char * restrict format, ...);

snprintf from <stdio.h> formats data into array s. For n > 0, it writes at most n - 1 characters plus terminating \0. Supply the actual available buffer capacity, not the pointer size.

Check result < 0 first: a negative return indicates an encoding error. Otherwise, the return is the required length excluding \0, and (unsigned int)result >= n means there is not enough room for the complete result including \0. Every nonnegative int fits in unsigned int, and the implicit conversions in this comparison preserve both values. Casting the return value to size_t instead can change a value greater than SIZE_MAX and hide truncation.

snprintf(NULL, 0, ...) writes nothing and allows length calculation. Argument types must match the format; copying between overlapping objects has undefined behavior.

Examples

#include <stdio.h>

int main(void)
{
    char buf[5];
    int result = snprintf(buf, sizeof buf, "%s", "abcdef");

    if (result < 0) {
        puts("encoding error");
        return 1;
    }
    printf("buffer: %s\nrequired: %d\n", buf, result);
    if ((size_t)result >= sizeof buf) {
        puts("truncated");
    }
    return 0;
}

Result

buffer: abcd
required: 6
truncated

The code and its stated output were verified in an isolated environment. The cast to `size_t` works here because the returned value `6` fits in that type. In general, use the `unsigned int` comparison described above.

Sources