vsnprintf
- C course
- Intermediate
- Lesson 79/116
- 5 min
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).
Practice 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);.
Starter code
#include <stdio.h>
#include <stdarg.h>
// format_into: safely format into buf
// declare va_list, init with va_start, write with vsnprintf, close with va_end
// main: char buf[64]; format_into(buf, 64, "Result: %d and %s", 10, "done"); printf("%s\n", buf);
int main(void) {
// write here
return 0;
}Sample 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;
}Expected output
Result: 10 and done
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is vsnprintf safer than vsprintf?
- it runs faster
- it uses less memory
- it takes no va_list
- it takes a size limit Correct answer
Explanation: vsnprintf takes a size parameter; this prevents overflow.
2 vsnprintf parameters
| Term | Meaning |
|---|---|
buf |
target string |
size |
max bytes |
fmt |
format |
args |
va_list |
3 The vsnprintf call
vsnprintf(buf, ____, fmt, args);
vsnprintf(buf, size, fmt, args);
Explanation: The size parameter prevents overflow.