How do I safely format floats/doubles with C's sprintf() ?
I'm porting one of my C++ libraries to a somewhat wonky compiler -- it doesn't support stringstreams, or C99 features like `snprintf()`. I need to format `int`, `float`, etc values as `char*`, and the only options available seem to be 1) use `sprintf()` 2) hand-roll formatting procedures.

Given this, how do I determine (at either compile- or run-time) how many bytes are required for a formatted floating-point value? My library might be used for fuzz-testing, so it needs to handle even unusual or extreme values.

Alternatively, is there a small (100-200 lines preferred), portable implementation of `snprintf()` available that I could simply bundle with my library?

Ideally, I would end up with either normal `snprintf()`-based code, or something like this:

    static const size_t FLOAT_BUFFER_SIZE = /* calculate max buffer somehow */;
    
    char *fmt_double(double x)
    {
        char *buf = new char[FLOAT_BUFFER_SIZE + 1];
        sprintf(buf, "%f", x);
        return buf;
    }


Related questions:

* [Maximum `sprintf()` buffer size for integers](http://stackoverflow.com/questions/3919995/determining-sprintf-buffer-size-whats-the-standard)
* [Maximum `sprintf()` buffer size for %g-formatted floats](http://stackoverflow.com/questions/1934071/sprintfbuf-20g-x-how-large-should-buf-be)
How do I safely format floats/doubles with C's sprintf() ?
===

I'm porting one of my C++ libraries to a somewhat wonky compiler -- it doesn't support stringstreams, or C99 features like `snprintf()`. I need to format `int`, `float`, etc values as `char*`, and the only options available seem to be 1) use `sprintf()` 2) hand-roll formatting procedures.

Given this, how do I determine (at either compile- or run-time) how many bytes are required for a formatted floating-point value? My library might be used for fuzz-testing, so it needs to handle even unusual or extreme values.

Alternatively, is there a small (100-200 lines preferred), portable implementation of `snprintf()` available that I could simply bundle with my library?

Ideally, I would end up with either normal `snprintf()`-based code, or something like this:

    static const size_t FLOAT_BUFFER_SIZE = /* calculate max buffer somehow */;
    
    char *fmt_double(double x)
    {
        char *buf = new char[FLOAT_BUFFER_SIZE + 1];
        sprintf(buf, "%f", x);
        return buf;
    }


Related questions:

* [Maximum `sprintf()` buffer size for integers](http://stackoverflow.com/questions/3919995/determining-sprintf-buffer-size-whats-the-standard)
* [Maximum `sprintf()` buffer size for %g-formatted floats](http://stackoverflow.com/questions/1934071/sprintfbuf-20g-x-how-large-should-buf-be)