How to check conversion of overflow char * [] to unsigned short
I am trying to convert user input to unsigned short:
int main(int argc, char *argv[])
{
unsigned short tl;
tl = (unsigned short) strtoul(argv[2], NULL, 0);
}
For example: user input "555555" overflows and becomes 31267.
How can I stop / check the overflow and also try to convert the input? What is the most efficient and effective way to stop this?
Thank you very much in advance.
+3
source to share
1 answer
If you look at the strtoul documentation at cppreference.com
If the converted value is out of bounds for the appropriate return type, a range error is raised and ULONG_MAX or ULLONG_MAX is returned.
You should discover this by checking errno
for ERANGE
.
So there should be something like this 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
}
+5
source to share