导致运行时错误

cin causes runtime error

本文关键字:运行时错误      更新时间:2023-10-16

问题在这里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上运行良好,并给出了正确的答案。然而,它给出了一个运行时错误的在线判断以及ideone。我已经调试了代码,错误是由cin >> n;引起的。没有它,它运行良好,并给出了正确的答案(1)。导致错误的测试输入是25,所以它不是一个大数字。我不知道到底是什么问题或它是如何导致错误。谢谢你。

这就是问题所在:

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

因为xd都从0运行到200,但at是堆栈上的数组,大小为:[200][200],因此显然x+d将覆盖数组声明后的代码。

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

(显然,初始化carry2也不会造成损害,但不这样做不会在0x0处提供核心转储,只是一些意想不到的行为)