From bec218c5d92d9d606129889fc2516093090ee41d Mon Sep 17 00:00:00 2001 From: Fabrice Bauzac Date: Sun, 14 Apr 2013 23:43:25 +0200 Subject: [PATCH] manual/arith.texi (strtoul): Document strtoul portability issues. --- ChangeLog | 4 ++++ manual/arith.texi | 23 ++++++++++++++++------- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/ChangeLog b/ChangeLog index 20be985..01732f4 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,7 @@ +2013-04-14 Fabrice Bauzac + + * manual/arith.texi (strtoul): Document strtoul portability issues. + 2013-04-08 Roland McGrath [BZ #14280] diff --git a/manual/arith.texi b/manual/arith.texi index ce8844e..9bdd5dc 100644 --- a/manual/arith.texi +++ b/manual/arith.texi @@ -2104,18 +2104,27 @@ The @code{wcstol} function was introduced in @w{Amendment 1} of @w{ISO C90}. @end deftypefun @comment stdlib.h -@comment ISO -@deftypefun {unsigned long int} strtoul (const char *retrict @var{string}, char **restrict @var{tailptr}, int @var{base}) +@deftypefun {unsigned long int} strtoul (const char *restrict @var{string}, char **restrict @var{tailptr}, int @var{base}) The @code{strtoul} (``string-to-unsigned-long'') function is like @code{strtol} except it converts to an @code{unsigned long int} value. The syntax is the same as described above for @code{strtol}. The value returned on overflow is @code{ULONG_MAX} (@pxref{Range of Type}). -If @var{string} depicts a negative number, @code{strtoul} acts the same -as @var{strtol} but casts the result to an unsigned integer. That means -for example that @code{strtoul} on @code{"-1"} returns @code{ULONG_MAX} -and an input more negative than @code{LONG_MIN} returns -(@code{ULONG_MAX} + 1) / 2. +@strong{Portability Note:} The behaviour of @code{strtoul} and other +unsigned variants, when used on strings depicting negative numbers, +varies between implementations. In particular, the BSD, Solaris and +GNU implementations differ from POSIX and @w{ISO C} specifications. +Prefer using the signed variants such as @code{strtol}, or explicitly +check for negativeness in @var{string}. + +The GNU implementation works by storing the sign independently of the +digits, converting the digits to an unsigned long value @var{n} +(reporting overflow if any), and then returning @var{n} or @math{-@var{n}} +according to the sign (without overflow checking). As a result, +@code{strtoul} returns overflow only when the input is +@math{-@code{ULONG_MAX}} or lower, or when the input is @code{ULONG_MAX} or +greater; otherwise, when the string depicts a negative number @var{n}, +@code{strtoul} returns @math{@code{ULONG_MAX}+1+@var{n}}. @code{strtoul} sets @var{errno} to @code{EINVAL} if @var{base} is out of range, or @code{ERANGE} on overflow. -- 1.7.9.5