I wanted to know how to make sure I'm not leaking memory when calling delete
on a singly-linked list (implemented by hand, btw).
I created these super basic list
,node
and person
classes to make myself a little bit clearer.
Here you go:
class person {
public:
person();
//something to do like sets gets etc...
virtual ~person();
private:
int id;
person* pplArr[5]; //Dynamically allocated person objs.
};
person::person(){
pplArr[5] = NULL;
}
person::~person(){
for(int i = 0; i < 5; i++)
delete pplArr[i];
}
#include "person.h"
class node {
public:
node(person*, node*);
person* getData();
node* getNext();
void setNext(node*);
virtual ~node();
private:
person* data;
node* next;
};
node::node(person* p, node* n){
data = p;
next = n;
}
person* node::getData(){
return data;
}
node* node::getNext(){
return next;
}
void node::setNext(node* nxt){
next = nxt;
}
node::~node(){
//nothing to delete "manually".
}
#include "node.h"
class list {
public:
list();
node* getFirst();
void insert(person*);
virtual ~list();
private:
node* first;
};
node* list::getFirst(){
return first;
}
void list::insert(person* p){
if(first){
first->setNext(new node(p, NULL));
}
else {
first = new node(p, NULL);
}
}
list::~list(){
node* aux;
while (first){
aux = first->getNext();
delete first;
first = aux;
}
}
Okay, so as you can see we have these 3 classes:
person
contains an array of 5 people objects, dynamically allocated:
node
contains a pointer to next
node, and data
which contains the actual person
object. and,
list
that contains the nodes
and manages them.
In order to successfully deallocate all the memory, I need call delete listName
, this line will go into each node and call delete
for each node
, which will in itself call the delete
for person
.
The delete
for person will go into each array slot and call the 'delete' of those persons to release that memory.
After that, it will execute the other deletes that are waiting. From bottom to top.
Is this correct? Are my destructors correct?
I would just like to know how to completely release the memory I allocated if there is a singly-linked list that contains nodes that have objects that have dynamically allocated memory.
I'm very confused, my apologies if this is nonsense or utterly bad implementation.
PS: I don't know if this list works, I just wanted to make a basic linked list to see if you guys could help me understand, so hopefully I can grasp the concept on actual, more complex lists. I am aware that there are linked lists and other data structures readily available on libraries but college teachers ask us to do it this way first.