Re: Implementation errors in strtol()

From: Matthias Andree <matthias.andree_at_gmx.de>
Date: Mon, 24 Jan 2005 19:04:12 +0100
Joerg Wunsch <j_at_uriah.heep.sax.de> writes:

> However, this immediately reminded me of Steinbach's Guideline for
> System Programming. ;-) (-> fortune -m Steinbach)

If a function be advertised
   to return an error code in the event of difficulties,
thou shalt check for that code, yea,
even though the checks triple the size of thy code
   and produce aches in thy typing fingers,
for if thou thinkest "it cannot happen to me",
the gods shall surely punish thee for thy arrogance.
  -- Henry Spencer, The Ten Commandments for C Programmers

> At least according to C99/Posix/SUSP, once you've caught conversion
> errors (by means of looking whether endptr had been advanced), and if
> you are sure that base had a legitimate value (as it is probably a
> hardcoded value in almost any practical application of strto*l), the
> only legitimate errno value remaining is ERANGE, as after a valid
> conversion and with a correct base value, there's no chance for EINVAL
> anymore.

The whole churn of this discussion can easily be fixed by a function
with a BSD license and a decent interface.

Outline:

/* returns true for success (putting output in *var), false for error */
int get_long(const char *in, long *var, int base)
  char *e;

  errno = 0;
  var = strtol(in, &e, base);
  if (e == in)
    return 0;
  if ((*var == LONG_MIN || *var == LONG_MAX) && errno == ERANGE)
    return 0;
  return 1;
}

I hope this covers everything. No, it does not expose e, that's left
as an exercise to the reader...
  
> Sure, you can check whether errno != 0 && errno != ERANGE, but see
> Steinbach, what to do in that case?  abort() ;-)

_Exit() to go out of the way of signals :-P

-- 
Matthias Andree
Received on Mon Jan 24 2005 - 17:04:22 UTC

This archive was generated by hypermail 2.4.0 : Wed May 19 2021 - 11:38:26 UTC