繁体   English   中英

为什么我在此代码中收到 SIGSEGV 错误?

[英]Why am i getting SIGSEGV error in this code?

对于问题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 向量或指针。

使用指针,您的代码可能如下所示(请注意,您必须删除您初始化的每个 memory):

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

使用向量,您的代码可能如下所示( std::vector为您处理所有 memory 管理):

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

可能导致 SIGSEGV 的一件事是对地址的无效写入。 例如,如果 K 小于 2,则您正在写入 memory 位置,您不安全地拥有并且操作系统可能会终止您的进程。 您的算法要么不适用于 K < 2,要么缺少边缘情况。

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

此外,您可能想检查您实际使用向量分配了多少 memory。

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

您正在尝试将您的号码的每个数字分配为 integer。 integer 通常需要大约 4 个字节,因此在困难的情况下,您的程序尝试分配4B * K = 3.64 TiB的 memory。 这可能是问题所在,因为我认为您手头没有数 TB 的 RAM。 您可能想尝试不同的尝试来解决没有分配那么多 memory 的难题。

注意:单个十进制数字需要少于 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM