#include <stdio.h>
#include <stdarg.h>


/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* From the man page, and only slightly tweaked, here's a  routine  that  is  a *
* version of snprintf that allocates a buffer for the message, and reallocates *
* it until it's big enough (or we run out of memory).  The return value points *
* to the message, so you can free it when you're done with it.                 *
*                                                                              *
* This routine is good for both glibc 2.0 and 2.1.  The reason for this is the *
* change in the return value of  vsnprintf.   In  older  libraries,  vsnprintf *
* returns -1 for failure due to buffer overflow; in newer libraries it returns *
* the size that the string would have been if the vsnprintf had succeeded.     *
*                                                                              *
* ToDo: Change the {size *= 2;} to something less draconian.                   *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
char * make_message(const char *fmt, ...)
{	int n, size = 100;	// Guess we need no more than 100 bytes.
	char *p;
	va_list ap;
	if (!(p = malloc(size))) {	// Initial allocation
		return NULL;
	}
	while (1) {		// Try to print in the allocated space.
		va_start(ap, fmt);
		n = vsnprintf(p, size, fmt, ap);
		va_end(ap);
		if (n > -1 && n < size) {	// If that worked, return the string.
			return p;
		}
		// Else try again with more space:
		if (n > -1) {		// glibc 2.1
			size = n+INC;	// precisely what is needed
		} else {			// glibc 2.0
			size *= 2;		// twice the old size
		}
		if (!(p = realloc (p, size)))
			return NULL;
	}
}

