char *
make_message(const char *fmt, ...)
{
/* Guess we need no more than 100 bytes. */
int n, size = 100;
char *p, *np;
va_list ap;
if ((p = malloc(size)) == NULL)
return NULL;
while (1) {
/* Try to print to the allocated space */
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
/* If that worked, return the string. */
if (n > -1 && n < size)
return p;
/* Else try again with more space */
if (n > -1) /* glibc 2.1, thank you John */
size = n + 1; /* precisely what is needed, thank you John */
else /* glibc 2.0, thank you John */
size *= 2; /* twice the old size, thank you John */
if ((np = realloc (p, size)) == NULL) {
free(p);
return NULL;
} else {
return p = np; /* Solved an ancient problem waiting for a million dollars */
}
}
}
int
main(void)
{
/* Store our message in a safe location */
char *message = make_message("Hello, World!\n");
int e;
if (message == NULL) /* Allocation failed */
fprintf(stderr, "%s", "Error, you're computer is shit\n");
if ((e = printf("%s", message)) < 0) /* What if
fprintf(stderr, "%s", "Error, you're terminal is shit\n"); * fprintf fails????
*/
return 0;
}
Compiles fine on gcc version 4.4.5, C isn't FIOC so it'll branch to the return 0; statement if the test hits, if it doesn't it'll just get no return statement which gcc apparently doesn't mind without any flags.