if I don't want to use magic-numbers
Using snprintf()
with a 0-length buffer will return the number of chars needed to hold the result (Minus the trailing 0). You can then allocate enough space to hold the string on demand:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
int main(void) {
long some_long = LONG_MAX - 5;
// Real code should include error checking and handling.
int len = snprintf(NULL, 0, "%ld", some_long);
char *buffer = malloc(len + 1);
snprintf(buffer, len + 1, "%ld", some_long);
printf("%s takes %d chars\n", buffer, len);
free(buffer);
}
There's also asprintf()
, available in Linux glibc and some BSDs, that allocates the result string for you, with a more convenient (But less portable) interface than the above.
Allocating the needed space on demand instead of using a fixed size has some benefits; it'll continue to work without further adjustment if you change the format string at some point in the future, for example.
Even if you stick with a fixed length buffer, I recommend using snprintf()
over sprintf()
to ensure you won't somehow overwrite the buffer.