[LTP] [PATCH v2 1/2] lib/safe_macros: Add SAFE_STRTOF

zhaogongyi zhaogongyi@huawei.com
Fri Dec 2 03:54:01 CET 2022


Hi Cyril,

> 
> > Hi!
> > > +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.
> 
> 

The exception cases may be described as:

 1. strtof return 0 when no conversion is performed, and endptr == nptr:  'rval == 0 && !strcmp(endptr, nptr)'

 2. strtof return HUGE_VAL or -HUGE_VAL when overflow:      '((rval ==HUGE_VAL) || (rval == -HUGE_VAL)) && errno == ERANGE'

 3. strtof retrun 0 and set errno to ERANGE when underflow:   'errno ==ERANGE && rval == 0'


So it may be write as:
	If (( errno == ERANGE && (rval == HUGE_VAL || rval == -HUGE_VAL || rval == 0))
	   || (rval == 0 && !strcmp(endptr, nptr)))

If the description as above is ok, I will resubmit the patch.

Regards,
Gongyi


More information about the ltp mailing list