Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does sscanf("123456789123456789123456789", "%d", &n) have defined behavior?

When sscanf() or another function from the scanf family is given a sequence of digits whose converted value exceeds the maximum value of the target integer type,

  • should the conversion be considered to have failed?
  • is the behavior defined at all?
like image 926
chqrlie Avatar asked Jun 24 '17 19:06

chqrlie


Video Answer


1 Answers

From the standard, 7.21.6.2p10 ((f)scanf, applies to the whole family):

… If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.

Looks like another reason to be very cautious with the scanf family. The strtoXX functions have a fully defined behaviour. They return LONG_MAX etc. for too large input and set errno == ERANGE. So if you need exact information, tokenise the input manually and use these functions for conversion. Another benefit: better error handling.

like image 122
too honest for this site Avatar answered Sep 19 '22 18:09

too honest for this site