Okay so I have this homework problem with c++ and deleting a dynamic array. When I run the program, it shows me the following: http://prntscr.com/p015e9 I guess the problem is something with deleting the pointers because i traced it to these lines:
delete[] _elementi1; _elementi1 = nullptr;
delete[] _elementi2; _elementi2 = nullptr;
This is my class and the error occurs when I call the "Dodaj" function
template<class T1, class T2 = int>
class FITKolekcija {
T1 * _elementi1;
T2 * _elementi2;
int _trenutno;
public:
FITKolekcija() {
_elementi1 = nullptr; // Elements 1 pointer
_elementi2 = nullptr; // Elements 2 pointer
_trenutno = 0; // This is the _current variable and is used as an iterator
}
~FITKolekcija() {
try {
delete[] _elementi1; _elementi1 = nullptr;
delete[] _elementi2; _elementi2 = nullptr;
}
catch (exception& e) {
cout << e.what() << endl;
}
}
T1 * GetT1() { return _elementi1; }
T2 * GetT2() { return _elementi2; }
int GetTrenutno() { return _trenutno; }
friend ostream& operator<< (ostream &COUT, FITKolekcija &obj) {
for (size_t i = 0; i < obj._trenutno; i++)
COUT << obj._elementi1[i] << " " << obj._elementi2[i] << endl;
return COUT;
}
void Dodaj(T1 clan1, T2 clan2) {
T1 *temp1 = new T1[_trenutno + 1];
T2 *temp2 = new T2[_trenutno + 1];
for (size_t i = 0; i < _trenutno; i++) {
temp1[i] = _elementi1[i];
temp2[i] = _elementi2[i];
}
delete[] _elementi1; _elementi1 = nullptr; // Here lies the runtime error
delete[] _elementi2; _elementi2 = nullptr;
temp1[_trenutno] = clan1;
temp2[_trenutno] = clan2;
_elementi1 = temp1;
_elementi2 = temp2;
_trenutno++;
//
}
}
With the following code, I get to execude "Dodaj" 7 times before the runtime error occurs with the following:
int main() {
int v6 = 6, v13 = 13, v32 = 32, v63 = 63, v98 = 98, v109 = 109, v196 = 196;
FITKolekcija<int, int> numbers;
cout << "1" << endl;
numbers.Dodaj(v196, v6);
cout << "2" << endl;
numbers.Dodaj(v13, v32);
cout << "3" << endl;
numbers.Dodaj(v98, v196);
cout << "4" << endl;
numbers.Dodaj(v63, v13);
cout << "5" << endl;
numbers.Dodaj(v98, v196);
cout << "6" << endl;
numbers.Dodaj(v196, v6);
cout << "7" << endl;
return 0;
}