Here's a trick you may find useful:
Every printf function (printf, fprintf, sprintf, snprintf, ...) returns the number of chars printed. In particular, snprintf() will return the number of chars that would be "printed" (including the final '\0' of the string), even if the buffer is too short. Example:
Code:
char buffer[2];
size = snprintf( buffer, 2, "%d", x ) - 1;
if x is 2łą-1 (2147483647), size will be 10.
And, of course, the segund argument (the size of the buffer), includes the final '\0'.
Knowing this you can write a routine that calculates the total size of the required buffer, allocate it with malloc() and use strcpy/strcat to fill it...
Good luck.