为什么我在这个代码中得到SIGSEGV错误?



为问题https://www.codechef.com/LRNDSA01/problems/MULTHREE

我得到运行时错误(SIGSEGV)。我用codechef写了下面的程序。我想知道具体是哪条指令在我的程序中产生了这个错误,这样我就可以尝试删除它。下面是代码:

#include <iostream>
using namespace std;
int main() 
{
int t;
cin>>t;
while(t--!=0)
{
int i,d0,d1,sum;
long long int K,digit=0;

cin>>K;
cin>>d0>>d1;
int arr[K];
arr[0]=d0;
arr[1]=d1;
sum=d0+d1;

for(i=2;i<=K-1;i++)
{
arr[i]=sum%10;
sum=sum+arr[i];
}

for(i=0;i<=K-1;i++)
digit=arr[i]+(digit*10);
//cout<<digit;
if(digit/3==0)
cout<<"YES";
else
cout<<"NO";
}
return 0;

}

编辑:实际可行的解决方案在最后。

首先,正如Ted Lyngmo已经说过的:你的数组初始化不符合c++标准(我认为一些编译器支持它,但我从来没有使用过它)。您可以使用c++ STL向量或指针。

使用指针,你的代码可能看起来像这样(注意,你必须删除你初始化的每一个内存):

int * arr = new int[K];
// Do your test case and before (!) the end of
// the while loop free the memory
delete[] arr;

使用向量,你的代码可能看起来像这样(std::vector为你照顾所有的内存管理):

#include <vector>
std::vector<int> arr(K);

可能导致SIGSEGV的一件事是对地址的无效写。例如,如果K小于2,您正在写入内存位置,您不安全拥有,操作系统可能会杀死您的进程。你的算法要么对K &lt不起作用;2或者缺少一个边缘情况

// Make sure that K >= 2
// If K < 2 the following lines could cause SIGSEGV
arr[0] = d0;
arr[1] = d1;

你可能还想检查你的向量实际分配了多少内存。

CodeChef上的任务指定:2 ≤ K ≤ 10^12

您正在尝试将您的号码的每个数字分配为整数。一个整数通常需要大约4字节,所以在困难的情况下,你的程序会尝试分配4B * K = 3.64 TiB的内存。这可能是问题,因为我不认为你有多个tb的RAM在手。您可能想尝试不同的方法来解决不分配那么多内存的难题。

注意:单个十进制数字的存储空间小于4位(半字节)。这仍然超出了你的分配能力。所以你可能想要考虑一个解决方案,你不必事先计算每一个数字,而是迭代你的未知数字的数字。

这是一个编译器错误,它需要知道数组的精确大小,你提供了一个在编译时未定义的变量,为了使它动态,你需要一个在运行时评估和创建的指针数组,在循环中声明变量是不好的,在开始时声明并使用它们。

#include <iostream>
#include <string>
int main() {
uint32_t * arr, K;

std::string in;
std::cout << "Array size -> ";
std::cin  >> in;
K = std::stoi(in);
arr = new uint32_t[K];
std::cout << "arr[0] -> ";
std::cin  >> in;
arr[0] = std::stoi(in);
std::cout << "arr[0] * 2 -> " << arr[0] * 2;
delete [] arr;
return 0;
}

最新更新