cin导致运行时错误

时间:2015-10-15 11:01:00

标签: c++ runtime-error cin

问题是https://www.hackerrank.com/challenges/extra-long-factorials 这是我的代码

#include <iostream>

using namespace std;

int main(){
    int n;
    cin >> n;
    int product[200];
    for (int i = 0; i < 200; i++)product[i] = 0;
    product[0] = 1;
    for (int i = 1; i <= n; i++){
        int a[200], res[200];
        for (int j = 0; j < 200; j++)a[j] = 0, res[j] = 0;
        int n = i;
        int k = 0;
        while(n != 0){
            a[k] = n % 10;
            n = n / 10;
            k++;
        }
        int at[200][200];
        for (int p = 0; p < 200; p++){
            for (int h = 0; h < 200; h++){
                at[p][h] = 0;
            }
        }
        int carry = 0;
        for (int x = 0; x < 200; x++){
            for (int d = 0; d < 200; d++){
                at[x][x+d] = ((product[d] * a[x]) % 10) + carry;
                carry = (product[x] * a[d]) / 10;
            }
        }
        int carry2, temp;
        for (int u = 0; u < 200; u++){
            temp = 0;
            for (int e = 0; e < 200; e++){
                temp += at[e][u];
            }
            temp = (temp + carry2);
            carry2 = temp/10;
            res[u] = temp %10;
            product[u] = res[u];
        }
    }
    int f = 0;
    for (; f < 200; f++){
        if(product[200-f-1] != 0)break;
    }
    for (; f < 200; f++){
        cout << product[200-f-1];
    }       
    return 0;
}

它在我的mac上的gcc上正常运行并给出正确的答案。然而,它给在线评判以及想法提供了运行时错误。 我调试了代码,错误是由cin >> n;引起的。没有它就可以正常运行并给出正确答案(即1)。导致错误的测试输入是25,所以它不是一个大数字。我不知道究竟是什么问题或者它是如何导致错误的。谢谢。

1 个答案:

答案 0 :(得分:4)

这是问题所在:

at[x][x+d] = ...

因为xd都从0运行到200,但at是堆栈中的数组,大小为:{{1}很明显[200][200]会覆盖数组声明之后的代码。

这是一个经典的缓冲区溢出:)

(显然,初始化x+d也不会受到伤害,但是这样做不会导致carry2的核心转储,只是一些意外的行为)

相关问题