I have the following C code to copy a linked list(taken from Stanford CS Library files):
struct Node* CopyList(struct Node* head)
{
struct Node* current = head;
struct Node* newList= NULL;
struct Node* tail= NULL;
while (current !=NULL)
{
if(newList==NULL)
{
newList=malloc(sizeof(struct Node));
newList->data=current->data;
newList->next=NULL;
tail= newList;
}
else
{
tail= malloc(sizeof(struct Node));
tail= tail->next;
tail->data=current->data;
tail->next = NULL;
}
current= current->next;
}
return(newList);
}
I have the following as a part of my main function:
struct Node* head = NULL;
for (i=3; i >=1;i--) //insert 3 elements into the linked list
{ //push inserts elements in the front
Push(&head,i);
} //now a linked list 1->2->3->NULL is formed
struct Node* newlst= CopyList(head); // copies contents into a new linked list
I am compiling the code using Bloodshed Dev C++. I don’t get any compilation errors but when I run it, it just crashes. What could be the issue with this? Am I passing the right parameter to the CopyList function?
Your problem lies here, in the
elsebit:You are allocating a new node and setting
tailto point to it (in that first line). Then you are usingtailas if it’s the old tail. Specifically, that second line will give you a rogue pointer (as you haven’t initialised the new node with valid pointers), which will probably crash in the third line when you try to dereference it.You need something like:
Actually, looking back at your code, what you probably intended was:
which achieves the same result.
I suppose I should mention that you really ought to check the return values from
mallocin case you run out of memory. You can do this with something like:Without checks like that, you will get crashes when you run out of memory.