Skip to contentSkip to conversation

lib/safe_macros: Add SAFE_STRTOF

PATCH zhaogongyi via ltp 2 participants 2 messages Dec 2, 2022

lore
Share & tools
lore
#0 lore raw

Hi Cyril,

Quoted 19 lines

Hi!

Review

Quoted 12 lines
(quoted diff) +12 -0
+float safe_strtof(const char *file, const int lineno,
+		  void (cleanup_fn) (void), char *str,
+		  float min, float max)
+{
+	float rval;
+	char *endptr;
+
+	errno = 0;
+	rval = strtof(str, &endptr);
+
+	if ((errno == ERANGE) || (rval == 0)
+	    || (rval == HUGE_VAL) || (rval == -HUGE_VAL)) {

This does not look right, supposedly the ERANGE is only set on overflow, and the rval is not guaranteed to be exact on underflow. Also rval == 0 is a valid result.

According to man 3 strtof, it seems there are some cases like:

1. strtof return the converted value as normal
2. strtof return 0 when no conversion is performed, and endptr == nptr: 'rval == 0'
3. strtof return HUGE_VAL or -HUGE_VAL when overflow: '(rval == HUGE_VAL) || (rval == -HUGE_VAL)'
4. strtof retrun 0 and set errno to ERANGE when underflow: 'errno == ERANGE'

For 2, it seems need to add checking of endptr when 'rval == 0' like: (rval == 0 && !strcmp(endptr, nptr)

Other places seem to be fine.

Regards,
Gongyi

Signature · 1 line
Mailing list info: https://lists.linux.it/listinfo/ltp
#1 lore raw

Hi!

Quoted 4 lines

According to man 3 strtof, it seems there are some cases like:

1. strtof return the converted value as normal
2. strtof return 0 when no conversion is performed, and endptr == nptr: 'rval == 0'

We can ignore this case since we check that the string was consumed later on. That's the:

+ if (endptr == str || (*endptr != '\0' && *endptr != '\n')) {
+ tst_brkm_(file, lineno, TBROK, cleanup_fn,
+ "Invalid value: '%s'", str);
+ return 0;
+ }

Quoted 2 lines

3. strtof return HUGE_VAL or -HUGE_VAL when overflow: '(rval == HUGE_VAL) || (rval == -HUGE_VAL)'
4. strtof retrun 0 and set errno to ERANGE when underflow: 'errno == ERANGE'

My manual says that the value is no larger than DBL_MIN, FLT_MIN, or LDBL_MIN in this case. Either way I would avoid checking the returned value in the case errno was set.

Quoted 1 line

For 2, it seems need to add checking of endptr when 'rval == 0' like: (rval == 0 && !strcmp(endptr, nptr)

Again, no need to check the actual return value, we can just check that the string was consumed, which we already do.

Signature · 5 lines
Cyril Hrubis
[email protected]

-- 
Mailing list info: https://lists.linux.it/listinfo/ltp