Search code examples
cfloating-pointprintffloating-point-precisionformat-string

Adjust the decimal places in a format string programatically and safely


I am trying to figure out the best way to handle changing a format string on the fly in C without opening an uncontrolled format string vulnerability.

I have data in a struct which contains the floating point number and an unsigned integer number which corresponds to the number of significant figures for printing.

I would like to use the integer to generate the precision for format strings on the fly so that:

3 generates "%.3g"

21 generates "%.21g"

Is there a safe way to do this without opening my code up to exploits?


Solution

  • Yes, you're in luck. You need to make use of the precision field in the format string. In that, you can provide a .* notation and supply the corresponding integer argument holding the value of the precision.

    You can use the following pattern to make this happen, example with printf().

     printf("%.*g", int_precision, decimal_to_print)