Re: [patch] have rtprio check that arguments are numeric; change atoi to strtol

Previous message: [thread] [date] [author]
Next message: [thread] [date] [author]
From: Giorgos Keramidas
Date: Tuesday, January 4, 2011 - 3:36 am

On Sun, 2 Jan 2011 18:46:47 -0500, Eitan Adler <lists@eitanadler.com> wrote:

Since the pattern of converting strings to int-derivative values appears
multiple times, I'd probably prefer something like a new function that
does the parsing *and* error-checking, to avoid duplication of errno
checks, invalidchar checks, and so on, e.g. something like this near the
top of rtprio.c:

        #include <errno.h>
        #include <limits.h>
        #include <string.h>

        /*
         * Parse an integer from 'string' into 'value'.  Return the first
         * invalid character in 'endp', if endp is non-NULL.  The return value
         * of parseint is 0 on success, -1 for any parse error.
         */

        int
        parseint(const char *string, const char **endp, int base, int *value)
        {
                long x;

                errno = 0;
                x = strtol(string, endp, base);
                if (errno != 0 || endp == str || (endp != NULL &&
                    endp != str && *endp != '\0' && (isdigit(*endp) == 0 ||
                    isspace(*endp) != 0)))
                        return -1;
                if (x >= INT_MAX) {
                        errno = ERANGE;
                        return -1;
                }
                return (int)x;
        }

Then you can replace all the atoi() calls with:

        int x;

        if (parseint(argv[1], NULL, 0, &x) != 0)
                errx(1, "your message");

which is a relatively cleaner way of handling strtol() parsing errors,
without the associated clutter of checking properly all possible edge
cases at every call-point.

_______________________________________________
freebsd-hackers@freebsd.org mailing list
http://lists.freebsd.org/mailman/listinfo/freebsd-hackers
To unsubscribe, send any mail to "freebsd-hackers-unsubscribe@freebsd.org"
Previous message: [thread] [date] [author]
Next message: [thread] [date] [author]

Messages in current thread:
Re: [patch] have rtprio check that arguments are numeric; ..., Giorgos Keramidas, (Sun Jan 2, 12:29 pm)
Re: [patch] have rtprio check that arguments are numeric; ..., Giorgos Keramidas, (Tue Jan 4, 3:36 am)
Re: [patch] have rtprio check that arguments are numeric; ..., Giorgos Keramidas, (Tue Jan 4, 3:40 am)
Re: [patch] have rtprio check that arguments are numeric; ..., Giorgos Keramidas, (Tue Jan 4, 5:26 am)
Re: [patch] have rtprio check that arguments are numeric; ..., Giorgos Keramidas, (Tue Jan 4, 11:12 am)