C
vsnprintf
Learn safe formatting with vsnprintf.
vsnprintf
vsnprintf safely writes variable arguments into a string (a char array). Unlike vsprintf, it takes a size limit; this prevents overflow.
Signature: int vsnprintf(char *buf, size_t size, const char *fmt, va_list args). buf is the target string, size is the maximum bytes to write, fmt is the format, args is the va_list. The return value is the total number of bytes that would have been written; if it exceeds size, the output is truncated. This safety limit is missing in vsprintf, which risks overflow. Modern C code always prefers vsnprintf. Example: vsnprintf(buf, 64, "Result: %d", args).
The format_into example
Let's write a simple wrapper: format_into safely formats into a buffer. This is handy for building log messages or report lines.
Definition: void format_into(char *buf, int size, const char *fmt, ...) { va_list args; va_start(args, fmt); vsnprintf(buf, size, fmt, args); va_end(args); }. The second argument to va_start is fmt. vsnprintf writes to buf and prevents overflow beyond size. Call: char buf[64]; format_into(buf, 64, "Result: %d and %s", 10, "done");. After this buf holds Result: 10 and done. You can then print it with printf("%s\n", buf).
Exercise The format_into function
Write void format_into(char *buf, int size, const char *fmt, ...). Call va_list args; va_start(args, fmt); vsnprintf(buf, size, fmt, args); va_end(args);. In main do char buf[64];, format_into(buf, 64, "Result: %d and %s", 10, "done");, printf("%s\n", buf);.
Show example solution
#include <stdio.h>
#include <stdarg.h>
void format_into(char *buf, int size, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
vsnprintf(buf, size, fmt, args);
va_end(args);
}
int main(void) {
char buf[64];
format_into(buf, 64, "Result: %d and %s", 10, "done");
printf("%s\n", buf);
return 0;
}
Test yourself
-
Why is vsnprintf safer than vsprintf?
- it runs faster
- it uses less memory
- it takes no va_list
- it takes a size limit
Show answer
it takes a size limit — vsnprintf takes a size parameter; this prevents overflow.
-
vsnprintf parameters
- buf
- target string
- size
- max bytes
- fmt
- format
- args
- va_list
-
The vsnprintf call
vsnprintf(buf, ____, fmt, args);
Show answer
vsnprintf(buf, size, fmt, args);
Next lesson: Variadic patterns