cvs commit: src/sbin/badsect badsect.c

Bruce Evans bde at
Mon Jan 10 04:58:39 PST 2005

On Mon, 10 Jan 2005, Giorgos Keramidas wrote:

> On 2005-01-10 03:36, Bruce Evans <bde at> wrote:
> >On Wed, 5 Jan 2005, Giorgos Keramidas wrote:

> > >  	for (argc -= 2, argv += 2; argc > 0; argc--, argv++) {
> > > -		number = strtol(*argv, NULL, 0);
> > > -		if (errno == EINVAL || errno == ERANGE)
> > > +		errp = NULL;
> >
> > The variable pointed to by strto*()'s second parameter is an output
> > parameter; initializing it in the caller is bogus.
> Are strto*() functions always supposed to set endp to _something_, or is

Not quite.  They are passed a pointer to the end pointer
("char **restrict endptr" in the prototype), and set *endptr if and only
if endptr is non-null.

> there a case for them to attempt saving a few cycles by leaving it
> untouched, possibly set to garbage?  This is what I was trying to avoid.

>From the man page:

     If endptr is not NULL, strtol() stores the address of the first invalid
     character in *endptr.  If there were no digits at all, however, strtol()
     stores the original value of nptr in *endptr.  (Thus, if *nptr is not
     `\0' but **endptr is `\0' on return, the entire string was valid.)

The first sentence says that *endptr is always set if endptr is not
NULL.  The wording isn't very good.  It misuses NULL, and the first
sentence is mostly wrong about what is stored and needs to be modified
by the second sentence, and the third sentence gives too much emphasis
to a not very useful condition for the string being valid.

>From a draft C99 standard (n869.txt):

       [#5] [... if a number is found] A  pointer  to
       the  final  string  is  stored  in  the object pointed to by
       endptr, provided that endptr is not a null pointer.
       [#7]  [... if a number is not found] the value of nptr
       is  stored in the object pointed to by endptr, provided that
       endptr is not a null pointer.

This makes the 2 cases clear.  *endptr is either left pointing to the
next part of the string (which may or may not contain another number,
so its validity is context-dependent and the man page shouldn't use
the term "valid"), or *endptr is left pointing to the start of the
string to indicate a lexing error (then the whole string is invalid
although its first character might be valid).


More information about the cvs-all mailing list