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.
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
strtodfunctions' error handling (specifically for overflow and underflow) is tied to themath_errhandlingmacro, which dictates whethererrnoor floating-point exceptions are used. Crucially, ifMATH_ERRNOisn't advertised,errnomight 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 theendptrparameter, POSIX may seterrnotoEINVAL, 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.