itoa()c实现int min下溢 [英] itoa() c implementation int min underflow

查看:73
本文介绍了itoa()c实现int min下溢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在针对itoa()函数运行一些测试用例,但不断获得

I'm running some test cases against my itoa() function but keep getting

did not allocate memory for the int min value

我在做支票,但是我在这里想念它,这是什么?

I'm doing the check but it's something I'm missing here, what is it?

char *ft_itoa(int x) {
    char *s;
    size_t len;
    long int n;

    n = x;
    if (x == -2147483648)
        return (ft_strdup("-2147483648"));

    len = ft_intlen(n) + 1;
    if (!(s = (char*)malloc(sizeof(char) * len)))
        return (NULL);

    if (n == 0)
        s[0] = '0';

    if (n < 0) {
        s[0] = '-';
        n = -n;
    }
    s[len - 1] = '\0';
    while (n) {
        len--;
        s[len - 1] = (n % 10) + '0';
        n /= 10;
    }
    return (s);
}

推荐答案

此行:

if (x == -2147483648)

不执行您认为的操作.C没有负整数常量.这是一个无符号的int常量,值为2 ^ 31,可在其中应用一元减号运算符.这意味着表达式 x == -21 ... 将取决于编译器使用的C标准.

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.

如果您使用C99或C11,就可以了.有一个足够大的带符号类型-保证long long long对于这个数字足够大,因此x和-21 ...都将转换为long long然后进行比较.但是,如果您使用的是C89编译器,而您的计算机没有足够长的类型,那么您将遇到实现定义的行为:

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.

这就是人们说要使用limits.h的原因.并不是因为他们在书,而是因为这是危险的领域.如果您仔细查看limit.h包含的内容,很可能会找到这样的一行:

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.

除此之外,我看不到您发布的代码中的任何错误.如果这不是问题,则 ft_intlen ft_strdup 都是错误的.或者您在测试错误时调用函数(调用测试时,同样的问题也适用于-21 ...).

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).

这篇关于itoa()c实现int min下溢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆