strtonum(3) in FreeBSD?
Theo de Raadt
deraadt at cvs.openbsd.org
Wed Apr 13 19:39:28 PDT 2005
> strtonum came about because ping had a whole variety of issues with
> numerical arguments. i created a strtonum function for it that was pretty
> much special case. it doesn't take long to realize that there's also
> ping6. and another thing. so the interface was widened up some. but not
> too big. there was a lot of discussion about exactly what strtonum would
> do, what it wouldn't do, and how one would use it. you don't have to
> agree with our decisions, but it sounds like you're descending in on
> "strtol but not called strtol".
As Tedu explains, strtonum() was designed to resolve the way that
atoi() and strtol() are misused.
And not just in a few places, but everywhere.
Hundreds and thousands of places will take "57b" and say that is the
number 57, because they use atoi().
So people are told to use strtol().
People are saying that strtonum() is a poor interface. Here's how you
have to use strtol() correctly to handle all the cases:
errno = 0;
lval = strtol(buf, &ep, 10);
if (buf == '\0' || *ep != '\0')
if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
(lval > INT_MAX || lval < INT_MIN))
ival = lval;
[This is a quote from our manual page, please read it for more details
about how hard these interfaces are difficult to use perfectly]
This is why strtol() is not an atoi() replacement.
strtonum() is designed to be that replacement. It is easy to use, and
it is easy to take existing code using atoi() or strtol() [incorrectly
used most of the time, too] and convert them to use it.
That is the number 1 goal.
If you don't understand what strtonum()'s reasons for existance are,
of course you will judge it wrong.
If correcting all the atoi() and strtol() or strtoul() bugs in your
source tree doesn't matter to you, then please feel free to ignore
We just got really sick of copying that blob of code above all over
More information about the freebsd-current