assertion problem (destructor)

hi
i have problem with dealocating dynamic twodimensional array...i will paste code here and hope someone can help me...problem is in destructor of template class 'kolekcija' which i commented:

#include <iostream>
using namespace std;
class student
{
private:
char * imePrezime;
int brIndexa;
int godinaStudija;
public:
student();
student (char*,int,int);
~student();
char *getImePrezime(){return imePrezime;}
int getBrIndexa(){return brIndexa;}
int getGodinaStudija(){return godinaStudija;}
friend ostream & operator <<(ostream&,const student&);
};
ostream & operator <<(ostream & out,const student & a)
{
out<<"Ime i prezime: "<<a.imePrezime<<endl;
out<<"Broj indexa: "<<a.brIndexa<<endl;
out<<"Godina studija: "<<a.godinaStudija<<endl;
out<<"==============================================\n\n";
return out;
}
student::student()
{
imePrezime=new char[5];
strcpy(imePrezime,"nema");
brIndexa=0;
godinaStudija=0;
}
student::student(char *ip, int i, int g)
{
imePrezime=new char[strlen(ip)+1];
strcpy(imePrezime,ip);
brIndexa=i;
godinaStudija=g;
}
student::~student()
{
delete [] imePrezime;
imePrezime=NULL;
}

template <class T>
class kolekcija
{
private:
int brojac;
T *ptr [20];
public:
kolekcija()
{
brojac=0;
for (int i=0;i<20;i++)
{
ptr[i]=new T;
}
}
//~kolekcija()
//{
// for (int i = 0; i <20; i++)
// delete [] ptr[i];
// delete [] ptr;
//}
void addUKolekciju(T &a)
{
ptr[brojac]=&a;
brojac++;
}
void ispis()
{
for (int i=0;i<brojac;i++)
cout<<*ptr[i]<<endl;
}
void izbrisi (int a)
{
for (int i=a-1;i<brojac;i++)
{
ptr[i]=ptr[i+1];
}
brojac--;

}
};

void main()
{
student c("cuko",111,2); //ko je slusao ubp ili dbms znace zbog cega ovi nazivi :)
student d("maca",112,3);
student e("pujdo",113,4);
kolekcija <student> b;
b.addUKolekciju(c);
b.addUKolekciju(d);
b.addUKolekciju(e);
b.ispis();
b.izbrisi(2);
cout<<"Poslije brisanja drugog unesenog studenta: \n\n";
b.ispis();


}
In function:
1
2
3
4
5
void kolekcija<T>::addUKolekciju(T &a)
{
	ptr[brojac]=&a;
	brojac++;
}

ptr holds an array of pointers. But the assingment in the function looses the object that was previously there. The object(s) are premanentyl lost.

But even worse, you're replacing an entry that was allocated on the heap, with one that's on the stack, main()'s stack in this case.

When kolekcija<student> goes out of scope, the destructor attempts to delete the entries in the list, but the ones added in addUKolekciju were not from the heap. This corrupts the heap and leads to undefined behaviour.
Topic archived. No new replies allowed.