重新创建atoi函数max long long error

问题描述 投票:0回答:1

我在输出中遇到问题,尽管我定义了 max long long 的宏来处理溢出,但它仍然给了我错误的输出

# define LLONG_MAX 9223372036854775807LL

正如您在这里看到的最大 long long 的宏

#include "libft.h"

static int  iswhitespace(char c)
{
    if (c == ' ' || c == '\t' || c == '\n'
        || c == '\r' || c == '\v' || c == '\f')
        return (1);
    return (0);
}

仅用于空白的函数

static int  ft_result(int count, long long int n, int sign)
{
    if (count > 1)
        return (0);
    else if (n > LLONG_MAX && sign == -1)
        return (0);
    else if (n > LLONG_MAX && sign == 1)
        return (-1);
    else
        return (n * sign);
}

我认为问题出在这个计算结果的函数中

int ft_atoi(const char *str)
{
    int                 i;
    unsigned long long  n;
    int                 sign;
    int                 count;

    i = 0;
    n = 0;
    sign = 1;
    count = 0;
    if (str == NULL || (str != NULL && *str == '\0'))
        return (0);
    while (iswhitespace(str[i]))
        i++;
    while (str[i] == '-' || str[i] == '+')
    {
        if (str[i] == '-')
            sign *= -1;
        count++;
        i++;
    }
    while (str[i] >= '0' && str[i] <= '9')
        n = (n * 10) + (str[i++] - '0');
    return (ft_result(count, n, sign));
}

对于主要功能,我认为逻辑是可靠的,如果存在潜在的段错误,请指出

#include <stdio.h>

int main()
{
    printf("my atoi: %d || original : %d",ft_atoi("9999999999999999999999999"),atoi("9999999999999999999999999"));
}

如你所见,这只是功能之间的比较 输出:

我的atoi:1241513983 ||原:-1

c string segmentation-fault overflow atoi
1个回答
0
投票

请注意,

9999999999999999999999999
大于
INT_MAX

Cpp参考说:

...或者如果转换后的值超出 int 可表示的值范围,则会导致 未定义的行为

所以

atoi("9999999999999999999999999"))
是一个UB。它可以做任何意想不到或意想不到的事情。

© www.soinside.com 2019 - 2024. All rights reserved.