Search code examples
cprintfc89

How large buffer do I need?


For a double value stored in x, how large does buffer need to be in the function call below?

sprintf(buffer, "%.*g", DBL_DIG, x);

Solution

  • The worst case will be :

    • one minus - if number if negative
    • one decimal point .
    • DBL_DIG decimal digits
    • the exponent part that should not be greater that e+999 (*)
    • the terminating null

    So the size of buffer should be DBL_DIG + 8.

    (*) According to wikipedia page on [IEEE floating point] the exponent part for a double is at most 21023 < 10308. So the decimal representation of the exponent need at most 3 digits.

    Of course above stuff only has sense for IEEE754 compliant floating point implementations (thanks to Basile Starynkevitch for noticing)