I can not understand why the program crashes when a function is called:

template <class T>void set<T>::del(elem<T> *x){ if(count==1){ head=tail=NULL; count=0; }else{ if(x==head){ head=head->next; }else{ elem<T> *tmp=head; if(x==tail){ while(!(tmp->next==tail)){ tmp=tmp->next; } tail=tmp; }else{ while(!(tmp->next==x)){ tmp=tmp->next; } tmp->next=x->next; } } } //delete x->data; delete x; } 

In the place of commenting, when uncommenting falls. If you write with a change - falls. But when this is given the same value of the object, and not a link, or am I confusing something?

 template <class T> struct elem{ //Элемент списка T* data; elem* next; }; template <class T> struct set{ public: set():count(0),head(NULL),tail(NULL){}; set(set<T> &s); set(int c, T &m); // ~set(); //Деструктор void test(T* x); private: elem<T> *head; //Голова elem<T> *tail; //Хвост int count; //Количество элементов void del(elem<T> *x); //Удаление по адрессу элемента }; template <class T>elem<T> * set<T>::addh(T *x){ //Добавление в голову (протестировано) elem<T> *temp = new elem<T>; //Указатель на временный элемент temp->data=x; //Записываем указатель во временный элемент temp->next=head; //Записываем следующим элементом голову count++; return temp; //Возвращаем указатель на новый элемент } 
  • 2
    Can you put all the code somewhere? From this piece it is not very clear what is happening. - dzhioev
  • one
    It all depends on how memory is allocated for elem :: data. In the above code is not visible. - ganouver
  • You did not create temp-> data - you do not want to delete it. - gecube
  • Does it need to be deleted, or will it go away? - Sergey
  • It depends on how х was created, which is passed to the addh() function. - gecube

1 answer 1

See it.

 void blablabla() { .... my_class xi; set<my_class> list; list.addh(&xi); // все хорошо - добавить элемент мы можем // теперь если мы элемент грохнем, то выполнится инструкция // delete x->data; т.е. по сути delete xi; а xi аллоцирован на стеке // итого - программе снесет крышу. } 

It turns out that the most reliable is when adding an element to a container not to add oneself, but to design a new object that will be a copy of the added one, and add it to the container.

Those. The function should be rewritten as:

 template <class T>elem<T> * set<T>::addh(T *x) { elem<T> *temp = new elem<T>; T *xi = new T(x); // вот оно! temp->data=xi; temp->next=head; count++; return temp; }