samedi 30 juillet 2016

How to remove a double free or corruption error in C++?

I am getting this error when I am calling sum3=sum(h3);

int sum(list<int> &l);
int main(){
int n1,sum1=0;
int n2,sum2=0;
int n3,sum3=0;
cin >> n1 >> n2 >> n3;
list<int> h1(n1);
for(int h1_i = 0;h1_i < n1;h1_i++){
   int num;
   cin >> num;
   h1.push_back(num);
}
list<int> h2(n2);
for(int h2_i = 0;h2_i < n2;h2_i++){
   int num;
   cin >> num;
   h2.push_back(num);
}
list<int> h3(n3);
for(int h3_i = 0;h3_i < n3;h3_i++){
   int num;
   cin >> num;
   h3.push_back(num);
}

sum1=sum(h1);
sum2=sum(h2);
sum3=sum(h3);
do{
    if(sum1!=sum2&&sum2!=sum3)
    {
        h1.pop_front();
        h2.pop_front();
        h3.pop_front();
        sum1=0;sum2=0;sum3=0;
        sum1=sum(h1);
        sum2=sum(h2);
        //sum3=sum(h3);   //Error while adding this         
    }
    else if(sum1==sum2&&sum1!=sum3)
    {
        h3.pop_front();
        sum3=0;
        sum3=sum(h3);
    }
    else if(sum1==sum3&&sum2!=sum3)
    {
        h2.pop_front();
        sum2=0;
        sum2=sum(h2);
    }
     else if(sum2==sum3&&sum1!=sum3)
    {
        h1.pop_front();
        sum1=0;
        sum1=sum(h1);
    }
}while(sum1!=sum2&&sum2!=sum3);
cout<<sum1;
return 0;
}

int sum(list<int> &l)
{
int sum=0;
list<int>::iterator p;
for(p=l.begin();p!=l.end();p++){
    sum+=*p;
}
return sum;     
}

What can be the possible problem? I know that there is some memory allocation issue but I can't find it. Everything works fine if that very line is commented.

Aucun commentaire:

Enregistrer un commentaire