Portál AbcLinuxu, 3. prosince 2025 11:50
#include < iostream >
#include "cList.h"
using namespace std;
int main()
{
cout << "Linked List" << endl;
cout << "--------------" << endl;
cNode* n1 = new cNode("1");
cNode* n2 = new cNode("2");
cNode* n3 = new cNode("3");
cList zoznam;
zoznam.append(n1);
zoznam.append(n2);
zoznam.append(n3);
zoznam.append(new cNode(*n1));
zoznam.append(new cNode(*n1));
zoznam.append(new cNode(*n1));
zoznam.printContents();
cNode* n4 = new cNode("4");
cNode* n2_5 = new cNode("2.5");
zoznam.insert(n4, 10);
zoznam.insert(n2_5, 2);
zoznam.deleteNode(1);
zoznam.deleteNode(0);
zoznam.deleteNode(10);
cout<<"---------------------------"<< endl;
zoznam.printContents();
cList zoznam2 = cList(zoznam);
zoznam2.deleteNode(0);
zoznam2.deleteNode(0); // nezmaže mi nultý prvok vidim to na problem s kopirovacím konštruktorom
cout<<"------------Zoznam 1 - original---------------"<< endl;
zoznam.printContents();
cout<<"------------Zoznam 2 - kopia---------------"<< endl;
zoznam2.printContents();
delete n1; // hádže segmantation fault
delete n2;
delete n3;
delete n4;
delete n2_5;
return 0;
}
[/code]
Problémový kod z cList.cpp
[code]#include "cList.h"
using namespace std;
cList::cList()
{
first = NULL;
}
cList::cList(const cList &oldList) // kopíruje aj to čo už nemá byť v pamäti, predpokladám že preto mi nemaže to čo by malo
{
first = NULL;
if (oldList.getLength() > 0)
{
first = new cNode(oldList.first->getData());
cNode *tmp = first, *tmp2;
for (int i = 0; i < oldList.getLength(); i++)
{
tmp2 = new cNode(oldList.getNode(i)->getData());
tmp->setNext(tmp2);
tmp = tmp2;
}
}
}
cList::~cList() // tento deštruktor asi sposobuje segmentation fault
{
for(int i = 0;i < getLength();i++)
{
cNode *tmp = getNode(i); // funkcie getNode vráti uzol na danom indexe, funguje v iných častiach kodu, v nej by problem byť nemal
delete tmp;
}
delete first;
}
Ostatne časti kodu zatial nebudem posielať.. . Som si na 99% istý že problem je v tomto kode. Pridal som do zdrojaku komentáre že čo nefunguje. Pri kopirovaní celeho zoznamu sa skopiruje aj to čo by tam už nemalo byť neviem prečo:( V tom deštruktore idem asi zle na to uvolnovanie pamäte.. ale zase keď nemam v tom deštruktore nič tak mi to počas delete sekcie v main.c vypiš random vypis pamäte... Ďakujem :)
Řešení dotazu:
cList::~cList()
{
this->clear();
}
void cList::clear()
{
struct destroyer
{
destroyer(cNode *first)
: current(first)
{}
~destroyer()
{
this->operator ()();
}
void operator ()()
{
while (this->current) {
cNode *n = this->current;
this->current = n->getNext();
delete n;
}
}
cNode *current;
};
destroyer d(this->first);
d();
}
Tohle správně zdestruuje celý seznam, i pokud destruktor některého cNode vyhodí výjimku.
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.