0

I tried to implement a singly linked list for my homework. Everything seemed to work perfectly until I tried it with linked list of linked lists, it failed to free the linked list inside and left some leaks. What I've done wrong? Some say I just ignore it the OS will clean up for me, but I really don't want to leave leaks. Everything else seems ok, so I only post the destructor part.

template<typename T>
class linkedList
{
protected:
    node<T>* pHead;
    node<T>* pTail;
    int size;
public:
    linkedList() : pHead(nullptr), size(0), pTail(NULL) {};

    ~linkedList() { this->cleanup(); };

    void cleanup()
    {
        while (pHead) {
            node<T>* p = pHead;
            pHead = pHead->pNext;
            delete p;
        }
    };

I have tried it with different data types, and it works ok, but when I tried

auto l = new linkedList<linkedList<int>*>;

it failed to free the linked lists inside. What is wrong with this? I need to use pointer because sometimes I need to know if it is NULL or not.

Felis
  • 11
  • 2
  • 3
    You delete the nodes, but you probably don't delete the data wrapped by the nodes (which you shouldn't!) You need to do that manually outside the list class. – Some programmer dude Nov 08 '19 at 13:20
  • Might be related to this question: https://stackoverflow.com/q/2403020/10077 – Fred Larson Nov 08 '19 at 13:22
  • `auto l = new linkedList*>;` -- So you want `linkedList` to somehow figure out that the `linkedList*` data needs to have `delete` called on it? And how is it going to know that those pointers came from a call to `new`? Also, why are you using `new` to create the linked list? Why not: `linkedList*> l;`?; – PaulMcKenzie Nov 08 '19 at 13:28
  • If you need to tell the difference between an empty list and no list, use `std::optional>` and the problem will solve itself. – molbdnilo Nov 08 '19 at 14:07
  • I think I get it, thank you guys. – Felis Nov 08 '19 at 15:08
  • 1
    The line `delete p;` will call the node's destructor, so your implementation of `node` is relevant. Would you add that definition to your question? – JaMiT Nov 08 '19 at 17:33

0 Answers0