0

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
ike
  • 38
  • 6

1 Answers1

1

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)
user2864740
  • 60,010
  • 15
  • 145
  • 220
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261