Libc is Broken, Part 1a

Robert, I said “int”, not “long”.
The code you presented does not work for platforms where the two are
different. There is no strtoi so you get to use strtol and do the
extra range checking.

It also does not work because there is no
requirement that strtol set errno for any condition
but overflow and underflow. In particular for the empty string.

It also does not work because libc functions may
set errno when no error is detected. And, in fact, they
often do.

And, finally, it also does not work for strings like “010”.
You get 8, but you should get 10 when someone mumbles “decimal”.

Update: And while I am picking at you, it seems I
have to point you at the ctype man pages too. isdigit
is defined on the special value EOF and an integers within the range
of unsigned char.

In practice, what libc implementations do is something like

  #define EOF (-1)
  #define isdigit(_c) ((__somearray+1)[(_c)] & SOME_BIT)

That can and will core dump if you send a random signed character.

(Glibc has a misguided attempt at making things work for signed
characters also. They essentially add 128 and duplicate half the
table. That works fine unless you want the right answer.)

Comments are closed.