I want to allocate a dynamic memory to a buffer, and I am storing the data in it through vsprintf();
. I am creating a logging mechanism that requires the use of vsprintf and every time my data is different so I want to allocate dynamic memory to the buffer. But I don't know how I can get the size of the format
and va_list args
.
I have no clue from where I can start and how can I get the buffer length
Any help would be great.
Thank you!
CodePudding user response:
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 ((size_t)length < sizeof buffer) {
/* message is OK, allocate a copy */
str = strdup(buffer);
} else {
/* message was truncated, allocate a large enough array */
str = malloc(length 1);
}
if (!str) {
/* allocation error */
[...]
return -1;
}
if ((size_t)length >= sizeof buffer) {
/* format the message again */
va_start(args, fmt);
length = vsnprintf(str, length 1, fmt, args);
va_end(args);
}
/* store the message somewhere */
[...]
return length;
}