7 Nov 2004 mitr   » (Journeyer)

I have seen one too many instances of checking strtol () results wrong, so, for the record:

Update: Sigh, two too many, a portable check for empty input added.

To convert const char *str to a long, properly checking for overflow, invalid trailing characters and empty input, it is necessary to do the following:

char *p;
errno = 0;
result = strtol(str, &p, base);
if (errno != 0 || *p != 0 || p == str)
  error_handling ();

It is necessary to check both errno and *p; if you don't check errno, you get 0 for empty input and LONG_MAX or LONG_MIN for overflow or underflow. On empty input the return value is 0 and errno might be set to EINVAL; the portable way of checking for empty input is comparing p and str.

This will still accept strings that start with white space; check for !isspace((unsigned char)*str) if you want to reject them.

I hope that helps someone.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!