I have a Node list that each Node contains a pointer pointing to a Student variable (this is a class), and a pointer pointing to next Node. Here is my code for insertAtTail.
void studentRoll::insertAtTail(const Student &s) {
if (head == NULL) {
this->head = new Node;
this->head->next = NULL;
this->head->s = new Student(s);
this->tail = head;
}
else {
this->tail->next = new Node;
this->tail = this->tail->next;
this->tail->next = NULL;
this->tail->s = new Student(s);
}
}
I used valgrind to debug, and I got:
==11106== 16 bytes in 1 blocks are definitely lost in loss record 1 of 2
==11106== at 0x4C2D1CA: operator new(unsigned long)
(vg_replace_malloc.c:334)
==11106== by 0x402BE7: StudentRoll::insertAtTail(Student const&)
(studentRoll.cpp:15)
==11106== by 0x401CF1: main (testStudentRoll01.cpp:19)
==11106==
==11106== 16 bytes in 1 blocks are definitely lost in loss record 2 of 2
==11106== at 0x4C2D1CA: operator new(unsigned long)
(vg_replace_malloc.c:334)
==11106== by 0x402C5B: StudentRoll::insertAtTail(Student const&)
(studentRoll.cpp:22)
==11106== by 0x401E2C: main (testStudentRoll01.cpp:27)
==11106==
Can someone help me with it? I think there are some problems about:
this->head->s = new Student(s);
and
this->tail->s = new Student(s);
But I cannot delete them because I need these "Students." And there are pointers point to "Students."
Thanks!!
Update: here is my destructor
StudentRoll::~StudentRoll() {
Node *iter = head;
while (iter) {
Node *next = iter->next;
iter->s->~Student();
delete iter;
iter = next;
}
head = tail = NULL;
}