#include
#include
#include
#include
char *make_message(const char *fmt, ...);
int main(void) {
char *one = "this";
char *two = "is";
char *three = "becoming a string";
char *result = NULL;
result = make_message("%s %s %s", one, two, three);
if(result == NULL) {
fprintf(stderr, "Error - make_message(...) == NULL\n");
return 1;
} else {
printf("%s\n", result);
free(result);
}
return 0;
}
char *make_message(const char *fmt, ...) {
char *p = NULL;
size_t size = 30;
int n = 0;
va_list ap;
if((p = malloc(size)) == NULL)
return NULL;
while(1) {
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if(n > -1 && n < size)
return p;
/* failed: have to try again, alloc more mem. */
if(n > -1) /* glibc 2.1 */
size = n + 1;
else /* glibc 2.0 */
size *= 2; /* twice the old size */
if((p = realloc (p, size)) == NULL)
return NULL;
}
}