How should I verify that an integer value passed in from argv won't overflow?

You can use strtol for this. You'll first need to check if this function fails to convert the value. If it convert successfully, then check if the value is in the range of INT_MIN to INT_MAX:

errno = 0;
long x = strtol(argv[1], NULL, 10);
if (errno) {
    perror("conversion failed");
} else if (x < INT_MIN) {
    printf("value too small\n");
} else if (x > INT_MAX) {
    printf("value too big\n");
} else {
    printf("value = %ld\n", x);
}

Note that this will work whether long is the same size as int or larger.

If sizeof(long) > sizeof(int), the INT_MIN and INT_MAX checks will catch the cases where the value fits in a long but not an int. If sizeof(long) == sizeof(int), an out of range value will result in errno being set to non-zero to catch the error, and the INT_MIN and INT_MAX cases will never be true.

Tags:

C