【问题标题】:coding error or compiler's fault编码错误或编译器错误
【发布时间】:2015-02-27 11:34:15
【问题描述】:

我正在为学校的一个项目编写此代码,当我想尝试调试我的代码时,甚至在运行 main() 的第一行之前就遇到了分段错误,所以我想知道我的代码是否遗漏了什么或者是编译器的错。

#include <iostream>

using namespace std;

class poly
{
public: int a[1000000];
private:
int forx(int x);
public:
poly(){cout<<"add";}
~poly(){cout<<"kill";}
void add();
void sum(int *x,int *y);
void dif(int *x,int *y);
void mult(int *x,int *y);
void renew();
};
void poly::add()
{
int i,n;
cin>>n;
a[0]=n;
for (i=1; i<=n; i++)
{
    cin>>a[i];
}
}
int poly::forx(int x)
{
int s,i,p;
p=1;
for (i=1; i<=a[0]; i++)
{
    s+=p*a[i];
    p*=x;
}
return s;
}
void poly::sum(int *x,int *y)
{
int i,m=x[0]>y[0]?x[0]:y[0];
a[0]=m;
for (i=1; i<=a[0]; i++)
{
    a[i]=x[i]+y[i];
}
}
void poly::dif(int *x,int *y)
{
int i,m=x[0]>y[0]?x[0]:y[0];
a[0]=m;
for (i=1; i<=a[0]; i++)
{
    a[i]=x[i]-y[i];
}
for (i=a[0]; i>0; i--)
{
    if (a[i]!=0) break;
    a[0]--;
}
}
void poly::mult(int *x,int *y)
{
int i,j,k;
for (i=1; i<=(x[0]+y[0]-2); i++)
{
    j=0;
    k=y[0]-1;
    while (j+k!=i)
    {
        if (j+k>i) k--;
        if (j+k<i) j++;
    }
    while (j<x[0] && k>=0)
    {
        a[i]+=x[j]*y[k];
        k--;
        j++;
    }
}
}
void poly::renew () {
int i;
for (i=1; i<=a[0]; i++)
{
    cout<<a[i];
}
}

int main()
{
cout<<"starting";
poly w;
w.add();
poly h;
h.add();
poly o;
o.sum(w.a,h.a);
o.renew();
o.dif(w.a,h.a);
o.renew();
o.mult(w.a,h.a);
o.renew();
}

【问题讨论】:

  • 如果它在 main 的第一行之前出现段错误,您应该能够在保持段错误的同时显着减少程序。它会让你更容易看到出了什么问题......
  • 我的解决方案能帮您解决问题吗?

标签: c++ arrays oop segmentation-fault codeblocks


【解决方案1】:

对于int a[1000000];poly 类的大小非常大。制作(实际上您正在制作 3 个)此类(在堆栈上)的局部变量会导致分段错误。

您可以尝试将它们设为static 或将它们移动到全局范围或动态分配它们。

...
static poly w;
w.add();
static poly h;
h.add();
static poly o;
...

另一种解决方案是将arrays 替换为std::vector

public: int a[1000000];改成

...
public: std::vector<int> a;
...
poly() : a(1000000) {cout<<"add";}
...

现在你可以创建这个类的本地对象了。


另一个相关问题 Segmentation fault on large array sizes

【讨论】:

    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多