Search code examples
c++dynamic-memory-allocationbad-alloc

std::bad_alloc exception thrown when operator= method is called C++


I'm writing my very first class in C++, which is a polynomial, and I've come across a bad_alloc exception thrown when I perform

P=Q; //(P,Q being polynomials)

I suppose the fact that bad_alloc is thrown (and sometimes the process terminates with -1073741819 status) has little to do with the fact that the memory is full but more with the fact that is something fundamentally wrong abut the way I constructed my class (and it's my first time working with dynamic memory too). Any help is much appreciated.

class  Polinom
{
    int grad;
    int * coef;
public:
    Polinom(){ coef=new int; coef[0]=0; grad=0;}
    Polinom(int x, int *c);
    Polinom(int x) {coef=new int[x];}
    Polinom(const Polinom &);
    ~Polinom(){ delete[] coef; }
    Polinom operator=(Polinom);
};

Polinom::Polinom(int x, int * c)
{
    int i;
    coef=new int[x];
    for(i=0;i<x;i++)
    {
        coef[i]=c[i];
    }
}

Polinom::Polinom(const Polinom &Q)
{
    int i;
    grad=Q.grad;
    coef=new int[grad];
    for(i=0;i<grad;i++)
    {
        coef[i]=Q.coef[i];
    }
}

Polinom Polinom::operator=(Polinom Q)
{
    int i;
    delete[] coef;
    grad=Q.grad;
    coef=new int[grad];
    for(i=0;i<grad;i++)
        coef[i]=Q.coef[i];

    cout<<"finally";
    return (*this);
}

int main()
{
    int *v,*w;
    int i,n;

    cin>>n;
    v=new int[n];
    for(i=0;i<n;i++){ cin>>v[i]; }
    Polinom P(n,v);
    delete[] v;

    cin>>n;
    w=new int[n];
    for(i=0;i<n;i++){ cin>>w[i]; }
    Polinom Q(n,w);
    delete[] w;

    P=Q;

    return 0;
}

Solution

  • In your constructor

    Polinom::Polinom(int x, int * c)
    {
      int i;
      coef=new int[x];
      for(i=0;i<x;i++)
      {
        coef[i]=c[i];
      }
    }
    

    You forgot to update the value of grad to x. that causes Q.grad in your = operator to contain garbage and fails.

    Here is the changed code

    Polinom::Polinom(int x, int * c)
    {
      int i;
      grad = x;
      coef=new int[x];
      for(i=0;i<x;i++)
      {
        coef[i]=c[i];
      }
    }