HN
Today

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

This deep dive into C's strtod functions exposes a baffling landscape of non-portable error detection mechanisms and conflicting standards. It meticulously details how error handling for string-to-float conversions is surprisingly inconsistent across Standard C, POSIX, and common library implementations. The article resonates with C programmers who routinely encounter these subtle but critical differences, making it a valuable exploration of hidden complexity in foundational library functions.

12
Score
1
Comments
#6
Highest Rank
8h
on Front Page
First Seen
Oct 12, 4:00 AM
Last Seen
Oct 12, 9:00 PM
Rank Over Time
610999141825

The Lowdown

The author takes a forensic look at the strtod, strtof, and strtold family of functions in C, unearthing a significant lack of portability and clarity in their error-handling specifications. It reveals a surprising divergence between the C standard and POSIX, compounded by undocumented behaviors in popular C libraries like glibc and musl.

  • The strtod functions' error handling (specifically for overflow and underflow) is tied to the math_errhandling macro, which dictates whether errno or floating-point exceptions are used. Crucially, if MATH_ERRNO isn't advertised, errno might not be set.
  • Underflow detection is particularly problematic, as the C standard makes its reporting entirely optional, unlike POSIX which typically mandates errno = ERANGE.
  • The most common method for detecting invalid input (checking errno != 0) is shown to be non-portable. While Standard C dictates checking the endptr parameter, POSIX may set errno to EINVAL, a behavior that varies between implementations (e.g., glibc doesn't, musl does).
  • Linux man pages often document POSIX behavior without explicitly noting it as an extension, adding to the confusion regarding C standard conformance.

Ultimately, the article concludes that portably checking for errors in strtod functions requires a complex, multi-pronged approach that adapts to math_errhandling values and differentiates between Standard C and POSIX targets, highlighting a significant area where the C standard could benefit from clearer specification.