c++ - cin 导致运行时错误

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

最佳答案

问题是:

在[x][x+d] = ...

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

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

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

关于c++ - cin 导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33146751/

相关文章:

java - Logcat 中出现 java.lang.ExceptionInInitializerError 错误?

C程序卡住,甚至不进入主程序

c++ - 如何通过 bash shell cin a c++ 字符串 >= 1024 个字符?

c++ - 如何在不中断剩余代码的情况下仅 cin C++ 中的整数?

c++ - Mac/c++ 上的 ChaiScript std lib 在运行时寻找 dll

c++ - 程序错误地读取二进制文件的一个字节

c++ - 在没有 cin 的情况下从控制台获取输入?

c++ - 默认嵌套结构初始化

java - 当我运行我的程序时,我时不时会收到随机错误

c++ - 使用 std::cin 忽略/跳过标记