Using 'new' when creating a linked list

379 views Asked by At

I've been trying to create a linked list in C++. I am trying to avoid using the keyword new when creating it, but it doesn't seem to work

// Linked lists
struct Node 
{
    int value;
    Node *next;

    Node( int val ) : value( val ), next(nullptr) {};
};


int main() 
{
    vector<int> vec = { 2,5,7,1,4,7 };

    //insertian
    Node head(0); // we need to use a pointer
    Node* ptr = &head;

    for ( auto v : vec)
    {
        Node* temp = new Node( v ); // Node temp( v );
        ptr->next = temp; //ptr->next = &temp;
        ptr = ptr->next; 
    }
}

The code above works fine. But if I replace the code inside the loop with the commented lines, then it fails. I'm not sure why.

I was also informed that you need to perform a delete when using new. If using new cant be avoided then how can the delete be performed?

1

There are 1 answers

3
Sean On BEST ANSWER

Saying Node temp( v ) will create a local variable scoped to the for loop. On each iteration the local variable will be created, and at the end of the iteration destroyed.

You're storing a pointer to the local variable, which is undefined behaviour. What is probably happening is that the local variable is being created over the top of the old one on each iteration (also this is implementation dependent).

As you want the node to outlive the lifetime of the iteration you will need to allocate the node on the heap via new