diff --git a/src/lib/strnum.c b/src/lib/strnum.c index e97e2fc719..9479fc8e15 100644 --- a/src/lib/strnum.c +++ b/src/lib/strnum.c @@ -460,7 +460,9 @@ int str_to_float(const char *str, float *num_r) { char *endp; float num = strtof(str, &endp); - if (*endp != '\0') + /* strtof() performs no conversion for an empty string and leaves endp + pointing at str, so the *endp check alone would accept "" as 0. */ + if (endp == str || *endp != '\0') return -1; *num_r = num; @@ -471,7 +473,9 @@ int str_to_double(const char *str, double *num_r) { char *endp; double num = strtod(str, &endp); - if (*endp != '\0') + /* strtod() performs no conversion for an empty string and leaves endp + pointing at str, so the *endp check alone would accept "" as 0. */ + if (endp == str || *endp != '\0') return -1; *num_r = num; diff --git a/src/lib/test-strnum.c b/src/lib/test-strnum.c index 5432af940d..857857fe60 100644 --- a/src/lib/test-strnum.c +++ b/src/lib/test-strnum.c @@ -375,8 +375,10 @@ static void test_str_to_float(void) INVALID(0.1x), INVALID(0.1.2), INVALID(bad), + /* strtof()/strtod() consume nothing here, so endp stays at str */ + { "", -1, 0 }, }; - test_begin("str_to_int"); + test_begin("str_to_float"); for (i = 0; i < N_ELEMENTS(tests); ++i) { float val = 1234.0; double val2 = 1234.0;