If you are on a platform that supports POSIX or C99, you can use snprintf to calculate the size of the buffer you need. snprintf accepts a parameter indicating the size of the buffer that you are passing through; if the size of the string exceeds the size of this buffer, it truncates the output so that it fits into the buffer, and returns the amount of space that it should have placed for all the output. You can use the output of this to allocate a buffer that matches the exact correct size. If you just want to calculate the required buffer size, you can pass NULL as a buffer and a size of 0 to calculate how much space you need.
int size = snprintf(NULL, 0, "%.20g", x); char *buf = malloc(size + 1);
Remember free(buf) after you used it to avoid memory leaks.
The problem is that it will not work in Visual Studio, which still does not support C99. While they are something like snprintf , if the buffer went too small, it does not return the required size, but returns -1 , which is completely useless (and it does not accept NULL as a buffer, even with a length of 0 ).
If you don't mind truncating, you can simply use snprintf with a fixed-size buffer and make sure you don't overflow it:
char buf[30]; snprintf(buf, sizeof(buf), "%.20g", x);
Make sure you check your documents on the snprintf platform; in particular, some platforms cannot add trailing zero at the end of a line if the line is truncated, so you may need to do this yourself.
source share