On Tue, Nov 25, 2025 at 10:35:39AM +0200, Costa Shulyupin wrote:
> On Mon, 17 Nov 2025 at 20:55, Wander Lairson Costa <[email protected]> wrote:
> > To address this, introduce a new strtoi() helper function that safely
> > converts a string to an integer. This function validates the input and
> > checks for overflows, returning a boolean to indicate success or failure.
> 
> Why not use sscanf() for this purpose instead of adding a new utility 
> function?
> 

The strtoi implementation properly detects:

1. Empty strings - via the !*s check
2. Conversion errors - via errno from strtol
3. Trailing garbage - via *end_ptr check ensuring entire string was consumed
4. Integer overflow/underflow - via explicit lres > INT_MAX || lres < INT_MIN
   bounds checking

sscanf has the following limitations:

1. Trailing garbage is silently ignored

   int val;
   sscanf("123abc", "%d", &val);  /* Returns 1 (success), val=123, "abc" 
ignored */

   While you could use "%d%n" with character count checking, this becomes
   cumbersome and defeats the purpose of simplification.

2. Integer overflow has undefined behavior

   sscanf with %d doesn't guarantee overflow detection and may silently wrap
   values (e.g., 2147483648 -> -2147483648). There's no standard way to detect
   this has occurred.

3. No detailed error reporting (this is minor, though)

   sscanf only returns match count, not error type. You cannot distinguish
   "bad format" from "overflow" from "trailing garbage".

> Also, using a boolean to return success or failure does not conform to
> POSIX standards and is confusing in Linux/POSIX code.
> 

Ok, I will change it.

> Costa
> 


Reply via email to