You should not use vsprintf()
because there is no way to tell this function the size of the destination array. You should instead use vsnprintf()
and you can compute the length of the formatted string from the return value of vsnprintf()
.
Here is an example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int logstuff(const char *fmt, ...) {
char buffer[256];
char *str;
int length;
va_list args;
/* format the message into a local buffer */
va_start(args, fmt);
length = vsnprintf(buffer, sizeof buffer, fmt, args);
va_end(args);
if (length < 0) {
/* encoding error */
[...]
return -1;
}
if ((unsigned)length < sizeof buffer) {
/* message is OK, allocate a copy */
str = strdup(buffer);
} else {
/* message was truncated, allocate a large enough array */
str = malloc(length + 1U);
}
if (!str) {
/* allocation error */
[...]
return -1;
}
if ((unsigned)length >= sizeof buffer) {
/* format the message again */
va_start(args, fmt);
length = vsnprintf(str, length + 1U, fmt, args);
va_end(args);
}
/* store the message somewhere */
[...]
return length;
}