If you are on a platform that supports POSIX or C99, you should be able to use snprintf
to compute the size of the buffer you will need. snprintf
takes a parameter indicating the size of the buffer you are passing in; if the size of the string would exceed the size of that buffer, it truncates the output to fit into the buffer, and returns the amount of space it would have needed to fit the entire output. You can use the output of this to allocate a buffer that's the exact right size. If you just want to compute the size of the buffer you need, you can pass in NULL as the buffer and a size of 0 to compute how much space you need.
int size = snprintf(NULL, 0, "%.20g", x);
char *buf = malloc(size + 1); // Need the + 1 for a terminating null character
snprintf(buf, size + 1, "%.20g", x);
Remember to free(buf)
after you've used it to avoid memory leaks.
The problem with this is that it won't work in Visual Studio, which still does not support C99. While they have something like snprintf
, if the buffer passed in is too small, it does not return the size needed, but returns -1
instead, which is completely useless (and it does not accept NULL
as a buffer, even with a 0
length).
If you don't mind truncating, you can simply use snprintf
with a fixed size buffer, and be assured that you won't overflow it:
char buf[30];
snprintf(buf, sizeof(buf), "%.20g", x);
Make sure you check your platform docs on snprintf
; in particular, some platforms may not add a terminating null at the end of the string if the string is truncated, so you may need to do that yourself.