How to use sscanf correctly and safely

The scanf family of function cannot be used safely, especially when dealing with integers. The first case you mentioned is particularly troublesome. The standard says this:

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
undeļ¬ned.

Plain and simple. You might think of %5d tricks and such but you’ll find they’re not reliable. Or maybe someone will think of errno. The scanf functions aren’t required to set errno.

Follow this fun little page: they end up ditching scanf altogether.


So go back to your C professor and ask them: how exactly does C99 mandate that sscanf will report errors ?

Leave a Comment