This line:
if (x == -2147483648)
does not do what you think it does. C does not have negative integer constants. This is an unsigned int constant with the value 2^31, that you apply the unary minus operator on. This means that the expression x == -21...
will depend on the C standard your compiler uses.
If you use C99 or C11, you'll be fine. There is a signed type that is big enough - long long is guaranteed to be big enough for this number, so both x and -21... will be converted into long long and then compared. But if you're using a C89 compiler and your machine doesn't have a long enough type, you're hitting implementation-defined behavior here:
When an integer is demoted to a signed integer with smaller size, or an unsigned integer is converted to its corresponding signed integer, if the value cannot be represented the result is implementation-defined.
This is why people are saying to use limits.h. Not because they are being pedantic, but because this is dangerous territory. If you look closely at what limits.h contains, you'll most likely find a line like this:
#define INT_MIN (- INT_MAX - 1)
This expression actually has the correct type and value.
Other than that I can't see any errors in the code you posted. If this is not the problem either ft_intlen
or ft_strdup
are wrong. Or you're calling your function in testing wrong (the same problems apply to -21... when calling tests).
... s[len - 1] = '\0'; while (n) { len--; s[len - 1] ...
looks fishy. Too many minuses. – Ricimalloc()
indicates C++, the question is tagged both ... – Ricift_intlen
is important, you should show it, but if you don't want to show it then that's that. You also need to show the test cases where this fails. – Cocottemalloc
? – Softwood-2147483648
may exceed the range of typeint
because2147483648
exceeds the range of 32-bit signed integers. Use-2147483647-1
to compute -2**31 as a 32-bit value. – Dialectologyif (x == -2147483648)
.-2147483648
and-2147483647-1
have the same value, but likely different types. Except-2147483647-1
does have a problem on rare 32-bit non 2's complement platforms. – Doggerel