0

对于这个问题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;

}

4

2 回答 2

1

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

首先,正如 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 < 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 位(半字节)来存储。这仍然超出您的分配范围。因此,您可能想考虑一种解决方案,您不必事先计算每个数字,而是遍历未知数字的数字。

于 2021-01-27T19:28:28.907 回答
0

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

#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;
}
于 2021-01-27T19:41:53.360 回答