
Please note that return value strtol save to long type or long long type.
The depend on how many size of sizeof(long) or sizeof(long long), if sizeof(long) is 4 in 32-bit computer, then output array bound is out of range, if sizeof(long) is 8 in 64-bit computer, then output test_result=2147483648111 when you save return of strtol function as long at sizeof(long) is 8 status.
And in your code if (!isdigit((unsigned char) *p) && *p != '-' && *p != '+'), if check it should return false rather then return true. (Note that you set value of *result to 0).
And if (!isdigit((unsigned char) *p) && *p != '-' && *p != '+') should be if (!isdigit((unsigned char) *p) || *p == '-' || *p == '+'), because of when *p is not digit or *p is '-' or *p is '+', then should return false. *p is either not a number or - or +, there is only one status, so this mean if (!isdigit((unsigned char) *p) && *p != '-' && *p != '+') is alway check failed, code in if (!isdigit((unsigned char) *p) && *p != '-' && *p != '+') will never run.
see below code that I change type of result int to long when declare, so parameter is long* result.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <ctype.h>
#include <limits.h>
static bool
ReadDimensionInt(char **srcptr, long *result, const char *origStr)
{
char *p = *srcptr;
// printf("p=%s\n", p);
/* don't accept leading whitespace */
if (!isdigit((unsigned char) *p) || *p == '-' || *p == '+')
{
*result = 0;
printf("******conversion could not be performed\n");
return false; /* leave 'src' unmodified */
}
errno = 0;
*result = strtol(p, srcptr, 10);
if (errno == ERANGE)
{
printf("array bound is out of range\n");
return false;
}else if (errno == EINVAL){
printf("conversion could not be performed\n");
*result = 0;
return false;
}
return true;
}
int
main(void)
{
char *s = "2147483648111";
char *result;
long testresult = 1;
bool readok;
printf("sizeof long is %zu, signed long max is %ld\n", sizeof(long), LONG_MAX);
readok = ReadDimensionInt(&s, &testresult, s);
if (readok)
printf("test_result=%ld\n", testresult);
else
printf("read dimension failed\n");
return 0;
}
Run it will output:
sizeof long is 8, signed long max is 9223372036854775807
test_result=2147483648111