Search code examples
c++pointersconstructornodes

How can I delete the Error when creating pointers on C++? I this case I have to use raw pointers


I'm trying to make a linked list with a pointer to a template class called Node:

template <typename T>
class llnode

{
public:
    T key;
    llnode<T> *prev, *next;

    llnode()
    {

    };

    llnode(const T &k, llnode<T> *w = NULL, llnode<T> *y = NULL) : key(k), prev(w), next(y){};

    ~llnode()
    {
        delete this;
    }
};

But, when I run the program this code in the main function

llnode<int> *node;
node->key = 6;
llnode<int> *node1;
node->key = 2;

I get the error message:

403 cygwin_exception::open_stackdumpfile: Dumping stack trace to "NAME OF MY EXE".exe.stackdump

How can I create more nodes without getting the error? It happens when I have 2 nodes created, but when I have 1 it does it right.


Solution

  • When you use them in main your pointers are not initializated. This ends in Undefined Behavior.

    Do this:

    llnode<int> *node = new llnode<int>;
    node->key = 6;
    llnode<int> *node1 = new llnode<int>;
    node->key = 2;
    

    Also note that calling delete this; in the destructor causes an infinite loop (More info here). Remove the destructor and free the space manually or better use a Smart Pointers or RAII approach.