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

CScanfUndefined Behavior

C Problem Overview


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?

C Solutions


Solution 1 - C

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionchqrlieView Question on Stackoverflow
Solution 1 - Ctoo honest for this siteView Answer on Stackoverflow