Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

vsnprintf — formatting a va_list into a bounded buffer

vsnprintf formats arguments supplied through va_list. It limits writes to the buffer capacity, while its returned length lets you detect truncated output.

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

Syntax

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

vsnprintf works like snprintf, but accepts a va_list instead of ... arguments. Use it to build formatting wrappers.

n is the buffer capacity in bytes, including the final \0. For n > 0, it writes at most n - 1 output bytes and a terminator. For n == 0, it writes nothing; s may be NULL.

The result r is the required length without the terminator; a negative value indicates an encoding error. Check r < 0 first. If r is nonnegative and n > 0, (unsigned int)r >= n indicates truncation. Converting to unsigned int preserves every nonnegative int value, even if size_t cannot represent it.

Initialize the list with va_start and finish with va_end; the function does not do the latter. For another pass, use va_copy before consuming the list and finish the copy too. Argument types must match the format; overlapping copied objects cause undefined behavior. Pass untrusted text as data for %s, not as the format.

Examples

#include <stdarg.h>
#include <stdio.h>

static int format_to(char *dst, size_t cap, const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    int result = vsnprintf(dst, cap, fmt, args);
    va_end(args);
    return result;
}

int main(void)
{
    char buf[8];
    int result = format_to(buf, sizeof buf, "%s:%d", "item", 12345);
    if (result < 0) {
        return 1;
    }
    printf("text=%s\nneeded=%d\ntruncated=%d\n",
           buf, result, (unsigned int)result >= sizeof buf);
    return 0;
}

Result

text=item:12
needed=10
truncated=1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources