Search code examples
memorynodesdelete-operator

How to delete a pointer inside a node in a singly linked list


I am having a problem with deleting an object pointer inside a node. I'm wonder if I just delete a node, will the object pointer will be free too?

struct customer{
    int data;
    customer(int data){
        this->data= data;
    }
};
class Node{
    public:
    customer * c;
    Node * next;
    Node(customer *&x){
        this->c = x;
        this->next = nullptr;
    }
};
int main() {
    customer * khach = new customer(5);
    Node * node = new Node(khach);
    delete node;
}

Solution

  • No, deleting the Node object won't automatically free the memory allocated for the customer object. You'll need to explicitly delete khach; before or after delete node; to avoid a memory leak.