Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using 'new' when creating a linked list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading