Why strtol() returns -1 for very large numbers in C?
For example:
#include <stdio.h>
#include <string.h>
int main() {
long long i = strtoll("135898539853985649864867468746876587784760", NULL, 10);
printf("i = %lld\n", i);
return 0;
}
Why strtol() returns -1 for very large numbers in C?
For example:
#include <stdio.h>
#include <string.h>
int main() {
long long i = strtoll("135898539853985649864867468746876587784760", NULL, 10);
printf("i = %lld\n", i);
return 0;
}
Why strtol() returns -1 for very large numbers in C?
Code is mis-behaving due to using the wrong print specifier / variable combination. That is undefined behavior.
long long i = .... printf("i = %d\n", i);
should raise a warning with a well warning enabled compile. Save time and enable all warnings.
Use a matching print specifier / variable: @Jonathan Leffler @Ian Abbott
long long i = ....
...
// vvv
printf("i = %lld\n", i);
It would make more sense to use strtoll()
to convert a string to a long long
int main() {
// long long i = strtol("1358...
long long i = strtoll("135898539853985649864867468746876587784760", NULL, 10);
// printf("i = %d\n", i);
printf("i = %lld\n", i);
return 0;
}
Printing the value of errno
would indicate overflow. Testing the endptr
would indicate if some conversion occurred.
As strtoll()
may set errno
to a non-zero value, set to 0 just prior to the function call to well assess the function's effect afterward and code did not inherit some earlier non-zero value.
char *endptr;
errno = 0;
long long i = strtoll(some_string, &endptr, 10);
int errnum = errno;
printf("i = %lld\n", i);
if (some_string == endptr) {
puts("No conversion");
} else {
if (errnum == ERANGE) {
puts("Overflow");
} else if (errnum) {
puts("Implementation specific error");
}
}
Actually, strtol()
returns the correct value LONG_MAX
. You use the wrong format string - try printf("i = %lli\n", i);
. %d
is for outputting an ordinary int
.