HEllo
this is reaaally urgent, the deadline is within less than an hour and thirty minute, and I lost hope that I can fix the problem myself. I know it has to do with pointers and allocating memory dynamically. The assignment was to use operator overloading to add two sets (adding two sets by getting the union of the two sets, which means all the elements in both set but not repeated). I figured out a way to do so but I think this memory problem is the cause why it's not working
here is the constructor of the class set that I used:
set::set()
{
size = 0;
elements = new int [size];
}
for the two sets to be added I used this member function:
void set::setSet()
{
cout<<"Enter the size of the set: ";
cin>>size;
elements = new int [size];
cout<<"Enter the elements of the set: ";
for(int i=0; i<size; i++)
cin>>elements[i];
}
and here is the operator + overloading member function:
set set::operator +(const set& s2)
{
set result;
int inter = 0;
int *intersection = new int [inter];
for(int a=0; a<size; a++)
{
for(int j=0; j<s2.size; j++)
{
if(elements[a] == s2.elements[j])
{
inter++;
intersection[a] = elements[a];
}
}
}
result.size = (size + s2.size) - inter;
result.elements = new int [result.size];
int i = 0;
for(i=0; i<result.size; i++)
{
for(int j=0; j<size; j++)
{
result.elements[i] = elements[j];
}
}
bool same = false;
for(int k=i, j=0; k<result.size, j<s2.size; k++, j++)
{
for(int l=0; l<inter; l++)
{
if(s2.elements[j] == intersection[l])
same = true;
}
if (same == false)
result.elements[k] = s2.elements[j];
else if (same == true)
continue;
}
return result;
}
and here is the main:
#include<iostream>
#include"sets.h"
using namespace std;
int main()
{
set s1;
s1.setSet();
s1.printSet();
set s2;
s2.setSet();
s2.printSet();
set s3 = s1 + s2;
s3.printSet();
return 0;
}
I get the debug error only when I come to the overloading part, s3.
the errors are "heap corruption detected" or "debug assertion failed _block_type_is_valid phead- nblockuse"
Please Help me! Thanks!