Struct Destructor

I am having trouble figuring out how to setup a destructor for a struct.

Here are the items within the Node struct:

char title[MAX_CHAR1];
double length;
int views;
int likes;
Node *next;
Node *back;

(the struct is part of a linked list of items)

Every way I've tried setting up the destructor, I've gotten some sort of seg fault or double memory release error. Can anyone help?

Last edited on
I suspect the double free error indicates a failure to properly copy whatever object is supposed to delete stuff, and not a problem in the destructor. It could also be that you wrote the destructor incorrectly, the data structure has cycles, or something like that.

You should follow the Rule of Three, or explicitly delete the copy & move operations.

Please show enough code to compile.
Last edited on
It sounds like you're trying to create a destructor for a single Node. That most likely isn't what you want.

When it comes to pointers, you have to ask yourself, "who owns the data?" (who owns the data the pointer points to)?

Every next and back Node cannot own both its own next and back Node, otherwise you have a contradiction. So you have to make the distinction somewhere.

In this case, your linked list, which owns all the Nodes, should have the destructor.

e.g. something like:
1
2
3
4
5
6
7
Node* curr = root;
while (curr != nullptr)
{
    Node* next = curr->next;
    delete curr;
    curr = next;
}
Last edited on
To be clear about what Ganado said, your Node class doesn't need a destrutor at all.
Topic archived. No new replies allowed.