14 Mar 2009 movement   » (Master)

It's not just atol(), Nicholas

Nicholas Nethercote warns us against atol(). Sadly, he recommends using strtol() instead. This interface is almost as bad. If atol() is impossible to get right, strtol() has to be classified under the obvious use is wrong.

As a perfect example of how horrible strtol() is, let's look at his example code:

int i1 = strtol(s, &endptr, 0); if (*endptr != ',') goto bad;
int i2 = strtol(endptr+1, &endptr, 0); if (*endptr != ',') goto bad;
int i3 = strtol(endptr+1, &endptr, 0); if (*endptr != '\0') goto bad;
bad: /* error case */

Can you spot the bug? What about an input like ",2,3" ? Nicholas does mention that this code is broken for underflow or overflow (you must wrap every singe call like this: "errno = 0; strtol(...); if (errno...)") but either missed this or considered it irrelevant. It's just too hard to get right.

Just use the *scanf() family (yes, that's hard to use too). Be suspicious of any code using either strtol() or atol().

Syndicated 2009-03-14 12:03:00 (Updated 2009-03-14 12:16:29) from John Levon

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!