https://gcc.gnu.org/bugzilla/show_bug.cgi?id=44574

--- Comment #19 from Heiko Eißfeldt <heiko at hexco dot de> ---
(In reply to Joseph S. Myers from comment #0)
> The atoi function has undefined behavior if its argument is outside
> the range of int.  Thus, GCC should not use it for any user input that
> might be outside that range.
> 
> For example, -O4294967296 should act like -O3, but on 64-bit systems with
> glibc it acts like -O0 (glibc's atoi converts the return from strtol to int,
> thereby losing high bits).
> 
> In most cases (like the above), using strtol and saturating for input out
> of range of int is probably appropriate, but some cases may need errors for
> large input.  A helper function - like atoi, but saturating - may be
> appropriate.

I agree, in general
- atoi() should be substituted with atoi_sat(), an saturating version based on
strtol()
- atol() should be substituted with strtol()
- atoll() and atoq() should be substituted with strtoll()

Slight semantic change:
Return value zero was the only way to check for errors with ato[ilq] and atoll,
so the cases of 'a parsed zero' and 'nothing parsed at all' could not be
differentiated. When using strtol()/strtoll() now, zero becomes a regular valid
value.

When necessary more strict checks can then be performed during parsing:
- was anything parsed at all?
- overflow check when errno == ERANGE
- is the character following the number the expected one (if any)?

When using strtoul()/strtoull() as a substitute in cases where only positive
values are accepted, care has to be taken that the first character is not a
minus character, since then unsigned wraparound would be applied, which is
probably never expected.

Reply via email to