title: How do I safely format floats/doubles with C's sprintf()?
body: <p>I'm porting one of my C++ libraries to a somewhat wonky compiler -- it doesn't support stringstreams, or C99 features like <code>snprintf()</code>. I need to format <code>int</code>, <code>float</code>, etc values as <code>char*</code>, and the only options available seem to be 1) use <code>sprintf()</code> 2) hand-roll formatting procedures.</p>
  
  <p>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.</p>
  
  <p>Alternatively, is there a small (100-200 lines preferred), portable implementation of <code>snprintf()</code> available that I could simply bundle with my library?</p>
  
  <p>Ideally, I would end up with either normal <code>snprintf()</code>-based code, or something like this:</p>
  
  <pre><code>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;
  }
  </code></pre>
  
  <p>Related questions:</p>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/3919995/determining-sprintf-buffer-size-whats-the-standard">Maximum <code>sprintf()</code> buffer size for integers</a></li>
  <li><a href="https://stackoverflow.com/questions/1934071/sprintfbuf-20g-x-how-large-should-buf-be">Maximum <code>sprintf()</code> buffer size for %g-formatted floats</a></li>
  </ul>