-1

I was working on this code for a project on school and when I wanted to try debugging my code just got segmentation fault before even running the first line in main() so i was wondering if i miss something on my code or is the compiler's fault.

#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();
}
Mike Kinghan
  • 55,740
  • 12
  • 153
  • 182
piciaxel
  • 7
  • 2
  • If it segfaults before the first line in main, you should be able to reduce your program significantly while keeping the segfault. It will make it much easier to see what is going wrong... – Marc Glisse Feb 27 '15 at 11:38
  • Does my solution help you to solve the problem? – Mohit Jain Mar 05 '15 at 10:52

1 Answers1

2

Becase of int a[1000000];, size of poly class is very large. Making a (actually you are making 3) local variable(s) of this class (on stack) would give you segmentation fault.

You can try making them static or move them to global scope or alloc them dynamically.

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

Another solution is to replace arrays with std::vector

change public: int a[1000000]; to

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

Now you can create local objects of this class.


Another related question Segmentation fault on large array sizes

Community
  • 1
  • 1
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100