0
votes

I am writing a function in C++ to add a "data" of type 'int' to the end of a linked list.

void insert_back()
{
 int no;
 node *temp;
 cout<<"\nEnter the number"<<"\n";
 cin>>no;
 temp = head;
 if(temp != NULL)
 {
         while(temp != NULL)
                    temp = temp->next;
 }

 temp->next = (node*)malloc(sizeof(node));
 temp = temp->next;
 temp->data = no;
 temp->next = NULL;

}

However, at the line, temp->next = (node*)malloc(sizeof(node)), I get an access violation error(segmentation fault). I do not find anything fundamentally wrong. Can you please enlighten me on the issue?

4
It does not enter the loop. Instead a new node is initialized and it gets pointed at by temp. My main linked list is "list", so actually i need to give a statement: list = temp; at the end of the function. - J_B892

4 Answers

1
votes

If you want to get the last node of the list, just check if the next member is null or not as the next member of the last node is null.

In your code, you check temp is null or not instead of temp->next.

while(temp != NULL)
    temp = temp->next;

will get the temp be null when the loop is over.

Besides, you should also consider the condition where the head is null.

void insert_back()
{
    int no;
    node *temp;
    cout<<"\nEnter the number"<<"\n";
    cin>>no;
    temp = head;
    if(temp != NULL)
    {
        while(temp->next != NULL)
            temp = temp->next;
        temp->next = (node*)malloc(sizeof(node));
        temp = temp->next;
        temp->data = no;
        temp->next = NULL;
    }else{
        head = (node*)malloc(sizeof(node));
        head->data = no;
        head->next = NULL;
    }

}
0
votes

Just before that line executes, temp will be null. You then dereference it.

0
votes

The temp you are referring doesn't exist, temp is NULL. To correct this, instead of using temp!=NULL in the while loop condition, use temp->next!= NULL.

 while(temp->next!=NULL)
{
   temp = temp->next;
}

Node* new_node = (Node*)malloc(sizeof(Node));

new_node->data = no;
new_node->next = NULL;
temp->next = new_node;
-1
votes
while(temp != NULL)
    temp = temp->next;

The above code gets you to the last node in the list. So, you are suppose to add the node to temp itself rather than temp->next.

temp = (node*)malloc(sizeof(node));

And now the last node's child should be NULL.

temp->next = NULL;