问题“分段错误” [英] Issue of "segmentation fault"

查看:145
本文介绍了问题“分段错误”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决黑客级别问题(给出链接) -

[ ^ ]

我已经理解了这个问题并创建了一个解决问题的程序。但是当大量数据作为输入给出时会出现问题,因此编译器会给出分段错误即违规错误。它可以在没有任何错误的情况下使用少量输入。



请帮助我。我正在努力坚持使用C ++的基本语言功能,而不是使用指针或向量(准确地说)来解决问题。请看看代码。



/



我尝试过:



I am trying to solve a hacker rank problem ( link given) -
[^]
I have understood the problem and created a program to solve the problem. But the problem occurs when a large amount of data is given as input hence the compiler gives "segmentation fault" i.e a violation fault.It works with small amount inputs without any error.

Kindly help me with this.I am trying to stick with basic language features of C++ and not using pointer or vectors (to be precise) to solve the problem. Kindly have a look at the code.

/

What I have tried:

#include<iostream>

using namespace std;


int main()

{
    int n;
    int q;
    int column;
    int dummy;
    int b;
    int f;
    cin>>n>>q;
     int a[n][1000];

    for(int i=0;i<n;i++)
    {
        cin>>column;
      
        for(int j=0;j<column;j++)
        {
            cin>>dummy;
             a[i][j]=dummy;
        }
    }


      for(int l=0;l<q;l++)
      {
          cin>>b;
          cin>>f;
          cout<<a[b][f]<<endl;
      }


}

推荐答案

如果列> 100,您的代码将访问[i] [100],这会导致错误。 100不应该是硬编码的,而是根据列分配的。
If column > 100, your code will access a[i][100], which causes the error. The 100 should not be hard coded, but allocated based on column.


您发布的代码甚至不会编译,因为数组 a 是没有定义。



错误最有可能来自对该数组的超出绑定的写入权限。这意味着使用的索引( i j 此处)大于或等于相应的数组大小。< br $>




同时添加 a 缺少的定义:

Your posted code would not even compile because the array a is nowhere defined.

The error is most probably sourced by an out of bound write access to that array. That means that the used indexes (i and or j here) are greater or equal than the corresponding array sizes.


The missing definition for a has been added meanwhile:
int a[n][1000];

从用户读取时发生错误输入大于或等于1000的使用大小或负数。添加对该值的检查:

The error occurs when column read from user input is greater or equal than the used size of 1000 or negative. Add a check for that value:

if (column < 0 || column >= 1000)
{
    cout << "Invalid column value";
    return;
}

[/ EDIT]


您的代码有一些错误,如n,但也有一些逻辑错误,如每行的列输入。



Additonal:在运行时分配你可以使用内存分配。

Your code has some error like, the n, but also some logic error like the column input for every row.

Additonal: for allocation at runtime you can use memory allocations.
cout << "column value:";
cin>>column;
cout << "row value:";
cin>>row;
//I would use a better name like piArray (pointer to int Array)
int *a = new int[column*row];//allocate int array is useable

//at the ende
delete a;


这篇关于问题“分段错误”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆