I can't understand. While my function returning, from char in main, random number. Original atoi() returning -1. I'm currently using C11 version. I heard from someone, that's because of int overflow and i need return int from my function, but i'm currently returning long. How can i detect intOverflow if that's not a 2147483647
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool mx_isdigit(int c) {
return c >= 48 && c <= 57;
}
bool mx_isspace(char c) {
return (c >= 9 && c <= 13) || c == 32;
}
int mx_atoi(const char *str) {
long num = 0;
int sign = 1;
for (; mx_isspace(*str); str++);
if (*str == '-' || *str == '+') {
sign = *str == '-' ? -sign : sign;
str++;
}
for (; *str; str++) {
if (!mx_isdigit(*str)) {
break;
}
num = (num * 10) + (*str - '0');
}
return sign == -1 ? -num : 0 + num;
}
int main(void) {
char str[100] = "12327123061232712306";
printf("R: %d\n", atoi(str));
printf("M: %d", mx_atoi(str));
}
Inside your function int mx_atoi(const char *str) {...
, you are calculating a result of type long
, yet the function returns an int
; so if the result stored in num
of type long
does not fit in an int
, something will get lost (actually , since signed integral values are converted, the behaviour is "implementation-defined", i.e. compiler-dependant). The result could be truncated bitwise, yielding a number that "looks" rather different that the decimal number you entered. Cf., for example, this online C11 draft. The bold paragraph applies:
6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Make int mx_atoi(const char *str)
to long mx_atoi(const char *str)
, use a long
-variable to store the result, and don't forget to use format specifier %ld
instead of %d
in your printf
then.
Otherwise, if you need to stick to int
and you want to safely react on overflows, you could do something like
if (num > INT_MAX) {
return -1;
}
inside your loop. INT_MAX
is defined in limits.h