导致运行时错误
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] = ...
因为x
和d
都从0
运行到200
,但at
是堆栈上的数组,大小为:[200][200]
,因此显然x+d
将覆盖数组声明后的代码。
这是一个典型的缓冲区溢出:)
(显然,初始化carry2
也不会造成损害,但不这样做不会在0x0
处提供核心转储,只是一些意想不到的行为)
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 试图找出为什么我会收到运行时错误?
- 迭代二维矢量时发生运行时错误
- 调用 java 的回调() 时应用程序崩溃.由于 detatchThread 而获得运行时错误