The confusing strtoul() behavior

The most depressing thing of C functions could be that they are not straightforward.

strtoul(3) - Linux man page:

The strtoul() function returns either the result of the conversion or, if there was a leading minus sign, the negation of the result of the conversion represented as an unsigned value, unless the original (non-negated) value would overflow; in the latter case, strtoul() returns ULONG_MAX and sets the global variable errno to ERANGE.
In short, the strtoul() function converts a string successfully even if the string starts with a minus sign. This behavior seems to be confusing because the unsigned long type does not handle negative values.

I think the good way to use C functions safely is to substitute safe methods if possible. In the case of the strtoul() function, you can find the safe methods like safe_strtoul() in open-source codes. For example,

are worth trying.

Comments