user3270371 user3270371 - 2 years ago 123
C++ Question

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.

Answer Source

If you look at the documentation of strtoul on

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download