I've been having a very specific problem that I haven't found an answer to online. I am trying to implement an adjacency list for a graph so that I can practice BFS and DFS.
The way I have my code set up is that an array cell is a vertex that points to an adjacency endpoint (I called it an edge) which points to another endpoint etc. The final adjacency endpoint points to NULL; however, since I guess its an edge type, it tries to point to another NULL endpoint etc. This causes my lists to be crowded with Null pointers and causes the program to consume a ton of memory and time when trying to destruct said objects. Why are my Null pointers pointing to other Null pointers? Is there a way to fix this? Please let me know.
The final adjacency endpoint points to NULL; however, since I guess its an edge type, it tries to point to another NULL endpoint etc. This causes my lists to be crowded with Null pointers and causes the program to consume a ton of memory and time when trying to destruct said objects. Why are my Null pointers pointing to other Null pointers?
NULL is a pointer value which cannot be dereferenced, therefore a NULL pointer cannot, by definition, point to anything. Your NULL pointers are not pointing to other NULL pointers.
The actual problem: your code leaks memory and you delete things that are not allocated with new which results in undefined behavior.
Take
1 2 3 4 5 6 7 8 9
void adj_list::add_vertex() {
vertex* nvert=new vertex; // nvert points to a dynamically allocated vertex object.
nvert->u=sz+1;
nvert->first_edge=NULL;
nvert->visited=false;
array[nvert->u]=*nvert; // The contents of *nvert are copied to array[nvert->u]
sz++;
return; // The value contained by nvert is lost: memory leak.
}
for example.
Do you understand what's happening here with the comments I added?
Yes, your comments make a lot of sense to me. I completely forgot that the assignment operator copies content over and does not directly assign the contents of *nvert to the array.
In terms of deleting objected not allocated with new, are you talking about this for example:
*vertex temp= new vertex; //has an initialized pointer to an edge type
delete temp->first_edge;
If so, how exactly do I delete the contents of this pointer?
Thank you for your help.
edit: currently, I'm thinking about turning the structs into classes so that I can dynamically allocate all initialized objects; however, this seems like a work around and I think it would be helpful to know how exactly one deletes memory that wasn't allocated with new.