Re: [PATCH] Init errno before strto* calls.

Dave Chinner
2014-07-13T23:04:14Z

On Sun, Jul 13, 2014 at 07:38:08PM +0200, Arkadiusz Miśkiewicz wrote:
> Eric Sandeen noted that strtol(3) and friends require errno
> initialization. From (fresh) man page:
>
> NOTES
> Since strtol() can legitimately return 0, LONG_MAX,
> or LONG_MIN (LLONG_MAX or LLONG_MIN for strtoll()) on both
> success and failure, the calling program should set errno
> to 0 before the call, and then determine if an error
> occurred by checking whether errno has a non-zero
> value after the call.
>
> So do it.
> ---
> libxcmd/input.c | 5 +++++
> 1 file changed, 5 insertions(+)
>
> diff --git a/libxcmd/input.c b/libxcmd/input.c
> index 397a124..711b527 100644
> --- a/libxcmd/input.c
> +++ b/libxcmd/input.c
> @@ -153,6 +153,7 @@ cvtnum(
> char *sp;
> int c;
>
> + errno = 0;
> i = strtoll(s, &sp, 0);
> if ((i == LLONG_MIN || i == LLONG_MAX) && errno == ERANGE)
> return -1LL;

I think that just checking for (errno != 0) is better here, because
then we also catch errors from unsupported formats or invalid
strings (i.e. EINVAL).

i.e. if the result is out of range, then ERANGE is always returned,
so we don't need to check the actual value at all...

Both patches could be condensed down to a single patch that does:

+ errno = 0;
i = strtoll(s, &sp, 0);
+ if (errno)
+ return -1LL;

Cheers,

Dave.
--
Dave Chinner
david@fromorbit.com