summaryrefslogtreecommitdiffstats
path: root/lib/libc/stdlib/strtol.3
diff options
context:
space:
mode:
authorpjanzen <pjanzen@openbsd.org>1999-09-14 03:59:55 +0000
committerpjanzen <pjanzen@openbsd.org>1999-09-14 03:59:55 +0000
commit0cf4581ecccd27cd82cb7d27a4559de215f36d5d (patch)
treebb498cfee470810e5e4b55633e1f4db3b0b8760e /lib/libc/stdlib/strtol.3
parentprotect alignment (diff)
downloadwireguard-openbsd-0cf4581ecccd27cd82cb7d27a4559de215f36d5d.tar.xz
wireguard-openbsd-0cf4581ecccd27cd82cb7d27a4559de215f36d5d.zip
Supply examples and discuss limitations.
Diffstat (limited to 'lib/libc/stdlib/strtol.3')
-rw-r--r--lib/libc/stdlib/strtol.365
1 files changed, 64 insertions, 1 deletions
diff --git a/lib/libc/stdlib/strtol.3 b/lib/libc/stdlib/strtol.3
index e7435cf87a8..3e0d5e67c7c 100644
--- a/lib/libc/stdlib/strtol.3
+++ b/lib/libc/stdlib/strtol.3
@@ -33,7 +33,7 @@
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
-.\" $OpenBSD: strtol.3,v 1.5 1999/07/20 10:18:22 aaron Exp $
+.\" $OpenBSD: strtol.3,v 1.6 1999/09/14 03:59:55 pjanzen Exp $
.\"
.Dd June 25, 1992
.Dt STRTOL 3
@@ -147,6 +147,68 @@ In both cases,
.Va errno
is set to
.Er ERANGE .
+.Sh EXAMPLES
+Ensuring that a string is a valid number (i.e., in range and containing no
+trailing characters) requires clearing
+.Va errno
+beforehand explicitly since
+.Va errno
+is not changed on a successful call to
+.Fn strtol ,
+and the return value of
+.Fn strtol
+cannot be used unambiguously to signal an error:
+.Bd -literal -offset indent
+char *ep;
+long lval;
+
+\&...
+
+errno = 0;
+lval = strtol(buf, &ep, 10);
+if (buf[0] == '\e0' || *ep != '\e0')
+ goto not_a_number;
+if (errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN))
+ goto out_of_range;
+.Ed
+.Pp
+This example will accept
+.Dq 12
+but not
+.Dq 12foo
+or
+.Dq 12\en .
+If trailing whitespace is acceptable, further checks must be done on
+.Va *ep ;
+alternately, use
+.Xr sscanf 3 .
+.Pp
+If
+.Fn strtol
+is being used instead of
+.Xr atoi 3 ,
+error checking is further complicated because the desired return value is an
+.Li int
+rather than a
+.Li long ;
+however, on some architectures integers and long integers are the same
+size. Thus the following is necessary:
+.Bd -literal -offset indent
+char *ep;
+int ival;
+long lval;
+
+\&...
+
+errno = 0;
+lval = strtol(buf, &ep, 10);
+if (buf[0] == '\e0' || *ep != '\e0')
+ goto not_a_number;
+if ((errno == ERANGE && (lval == LONG_MAX || lval == LONG_MIN)) ||
+ (lval > INT_MAX || lval < INT_MIN))
+ goto out_of_range;
+ival = lval;
+.Ed
.Sh ERRORS
.Bl -tag -width Er
.It Bq Er ERANGE
@@ -156,6 +218,7 @@ The given string was out of range; the value converted has been clamped.
.Xr atof 3 ,
.Xr atoi 3 ,
.Xr atol 3 ,
+.Xr sscanf 3 ,
.Xr strtod 3 ,
.Xr strtoul 3
.Sh STANDARDS