简体   繁体   中英

How to check for overflow converting char*[] to unsigned short

I am trying to convert a user input into unsigned short:

int main(int argc, char *argv[])
{
    unsigned short tl;
    tl = (unsigned short) strtoul(argv[2], NULL, 0);
}

For example: a user input of "555555" overflows and becomes 31267.

How can I stop/check for overflows while also trying to convert the input? What is the most efficient and effective way to stop that from happening?

Many thanks in advance.

If you look at the documentation of strtoul on cppreference.com

If the converted value falls out of range of corresponding return type, range error occurs and ULONG_MAX or ULLONG_MAX is returned.

You should be able to detect this by checking errno for ERANGE .

Something like this should therefore work for you:

#include <limits>
#include <cerror>

auto n = strtoul(argv[2], NULL, 0);
if (errno == ERANGE || n > std::numeric_limits<unsigned short>::max()) {
  // Handle overflow
}
else {
  // Do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM