#include #include #include #include int mprintf (char ** p, const char *format, ...) { va_list arg; int done=0; int len = 0; int add_len = 0; /* count old chars */ if(*p) len = strlen(*p); /* count leng to add + 1 extra for the '\0' */ add_len = strlen(format) + 1; printf("Changing size to %i\n", len + add_len); *p=realloc(*p, ((len + add_len) * sizeof(char))); while(1) { va_start (arg, format); done = vsnprintf ((*p)+len, add_len, format, arg); va_end (arg); /* check if that was enouth */ if(done > -1 && done < add_len) return(done); /* try increase it a bit. */ add_len = ( done < 0 ? add_len * 2 : add_len + 1); printf("Changing size to %i\n", len + add_len); *p=realloc(*p, ((len + add_len) * sizeof(char))); } return(-1); } int main(int argc, char **argv) { char *test=NULL; mprintf(&test, "Hello world\n"); mprintf(&test, "This is a funny test\n"); mprintf(&test, "Of an self reallocating function\n"); mprintf(&test, "that shud work with %s\n", "variables"); printf("This is test (%i): \n\"%s\"\n", strlen(test), test); free(test); exit(0); }