title: What is the minimum buffer size for sprintf with %g?
body: <p>The problem is to statically allocate a buffer large enough to fit a printed double, formatted with %g at maximum precision.  This seems like a simple enough task, bu I'm having trouble.  The best I have come up with (assuming the number to be printed is x) is</p>
  
  <pre><code>char buf[1 + DBL_DIG + DBL_DIG + 1 + 1 + 1 + DBL_DIG + 1];
  int len = sprintf(buf, "%.*g", DBL_DIG, x);
  </code></pre>
  
  <p>The DBL_DIG macro is from float.h, and apparently it is supposed to indicate the maximum precision for the type double.  We need:</p>
  
  <ul>
  <li>1 byte for a negative sign</li>
  <li>enough bytes to capture the significant digits</li>
  <li>at most one 'separator' char (comma, etc.) per digit</li>
  <li>1 byte for a decimal point</li>
  <li>1 byte for 'e'</li>
  <li>1 byte for the sign on the exponent</li>
  <li>some bytes for the exponent</li>
  <li>1 byte for the trailing null written by sprintf.</li>
  </ul>
  
  <p>I'm using the number of significant digits as an upper bound on the number of digits in the exponent.  Have I made any errors?  Is there a better solution?  Should I just allocate 64, 128, or 256 bytes and hope for the best?</p>