Mail
Mail

Reputation: 334

Linked list deletion and duplication

In the code I copied newnode to the headnode and also to the temp node. But when I delete an instance of data, it seems to affect the other locations as well. When I freed newnode it also erases the content of head and temp .How is this happening?

Though I copied data initially, the data is freed. This is due to dereferencing? So what should I do if I want to have a copy list and want to manipulate this without affecting the original?

And I initially malloc'd the memory I want by malloc() but in later copy operations I see at codes they are not malloc()'ed rather just copied. And how is it still it working? Do my two questions have a relation?

#include <iostream>
#include <cstdlib>
using namespace std;   

struct node{
    int data;
    struct node*next;
};

int main()
{
    struct node*newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=2;
    newnode->next=NULL;
    struct node*head=NULL;
    head=newnode;
    struct node*temp=newnode;

    while(head!=NULL)
    {
        cout<<head->data;
        head=head->next;
    }

    cout<<temp->data;
    free(newnode);
    free(head);
    cout<<temp->data;
    return 0;
}

Upvotes: 0

Views: 86

Answers (1)

Paul Ogilvie
Paul Ogilvie

Reputation: 25296

With struct node *newnode=(struct node*)malloc(sizeof(struct node)); you allocate a piece of memory for a node once and then you assign the address of this memory to all other node pointers. So when you free this piece of memory, the node isn't available any more to any of the node pointers.

struct node *head=newnode;    // head now points to *newnode
struct node *temp=newnode;    // temp now also points to *newnode
...
free(newnode);    // newnode, head and temp point to released memory now
free(head);       // oops! head was released already by the previous statement

Note: this is the C explanation. In C++ the constructor of a class can do the memory allocation and a redefined assignment operator can create a new instance of the object (but I am not a C++ programmer).

The following function creates a copy of the list:

struct node *copylist(struct node *oldlist)
{
    struct node *newhead, *list;
    if (!oldlist) return(0);
    list= newhead= malloc(sizeof(struct node));
    *newhead= *oldlist;
    while (oldlist->next) {
        list->next= malloc(sizeof(struct node));
        oldlist= oldlist->next;
        list= list->next;
        *list= *oldlist;
    }
    list->next= NULL;
    return(newhead);
}

Upvotes: 1

Related Questions