hn.today

No portable way to detect string-to-float conversion errors in standard C

sebsite.pw3 points0 comments
Screenshot of No portable way to detect string-to-float conversion errors in standard C

Standard C ties error reporting for the string-to-floating conversions (strtod, strtof, strtold, etc.) to the math_errhandling macro, which can advertise support for errno (MATH_ERRNO) and/or floating-point exceptions (MATH_ERREXCEPT). If an implementation does not claim MATH_ERRNO, those functions are not required to set errno on overflow or underflow, and underflow reporting may be optional. POSIX, by contrast, mandates setting errno=ERANGE for overflow and underflow and even allows errno=EINVAL for an unparsable string; man pages on Linux generally omit noting that POSIX imposes stricter behavior. In practice different libc implementations behave differently: glibc never sets errno for a non-conversion, while musl sets EINVAL, so errno-based checks are not portable across conforming implementations.

A practical, standards-aware approach requires clearing both the floating-point exception flags and errno before calling a conversion, then inspecting math_errhandling to decide whether to test errno==ERANGE or to test FE_OVERFLOW/FE_UNDERFLOW after the call; even so, underflow detection can remain unreliable because it is implementation-defined. For invalid input the only portable check is to use endptr and compare it to the input pointer. If strict, portable underflow detection is required, the only robust option may be manual parsing of the significand/exponent to determine whether a true subnormal or zero result was produced.

Read on sebsite.pw0 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Security

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.