byronwatt / CmdLineOptions

yet another command line parser for c++
MIT License
1 stars 0 forks source link

improve error checking for int/uint arguments #37

Open byronwatt opened 1 year ago

byronwatt commented 1 year ago

instead of using strtol/strtoul which doesn't check for larger than 2^31/2^32,

instead use strtoll/strtoull and look at the uint64_t/int64_t and generate an error if it overflows.

I'm not sure how if there's an easy way to check for overflow for int64/uint64,... could craft our own function, or if the result is MAX_INT64/MAX_UINT64, could check if stricmp of the sprintf("%x" PRIx64 ",value) matches.

For microchip purposes, we only use this function for internal test scripts which currently do not use values close to 18,446,744,073,709,551,616 e.g. current scripts are mostly in the 8 digit hex numbers,... haven't had to worry about accidentally typing 17 digits instead of 16 digit hex numbers.

pointnotfoe commented 1 year ago

Could any of these help? https://cplusplus.com/reference/limits/numeric_limits/

On Sun, Nov 6, 2022 at 12:44 AM Byron Watt @.***> wrote:

instead of using strtol/strtoul which doesn't check for larger than 2^31/2^32,

instead use strtoll/strtoull and look at the uint64_t/int64_t and generate an error if it overflows.

I'm not sure how if there's an easy way to check for overflow for int64/uint64,... could craft our own function, or if the result is MAX_INT64/MAX_UINT64, could check if stricmp of the sprintf("%x" PRIx64 ",value) matches.

For microchip purposes, we only use this function for internal test scripts which currently do not values close to 18,446,744,073,709,551,616 e.g. current scripts are mostly in the 8 digit hex numbers,... haven't had to worry about accidentally typing 17 digits instead of 16 digit hex numbers.

— Reply to this email directly, view it on GitHub https://github.com/byronwatt/CmdLineOptions/issues/37, or unsubscribe https://github.com/notifications/unsubscribe-auth/ADLPK72PFQ5UDDRLJAM57P3WG5OXJANCNFSM6AAAAAARYJV5NE . You are receiving this because you are subscribed to this thread.Message ID: @.***>

byronwatt commented 1 year ago

the problem is,... and i didn't know this,

is that strtoul("4294967296") returns 0 !!!!!! without any indication that it was actually 2^32 and wrapped.

byronwatt commented 1 year ago

example code showing strtoul fine with numbers larger than 2^32

https://onlinegdb.com/p2rkZ8wkB

byronwatt commented 1 year ago

oh,... strtol returns a long int which is 64 bit on most computers these days, although 32 bit embedded systems still have long defined as 32 bit.

so on 64bit targets, strol and strtoll are the same function.

either way, some checking could be useful.

problem is I'm just too old: when I grew up, strtol returned a 32 bit integer !