0
votes

I'm trying to insert a new node at the end of a linked list. However, when I try, I get a segmentation fault at what would be the point of insertion. I know that the preferred method is the 'head -> next' style, but for the assignment, we're stuck doing it long hand. Help?

Thanks!

#include <iostream>
using namespace std;

struct NodeType;
typedef NodeType *NodePtr;

struct NodeType
{
   int data;
   NodePtr next;
};

int main ()
{
   NodePtr head;
   NodePtr temp;
   NodePtr tempTwo;
   NodePtr tempThree;
   NodePtr tempFour;

   head = new NodeType;
   (*head).data = 5;
   (*head).next = NULL;

   temp = new NodeType;
   (*temp).data = 8;
   (*temp).next = head;
   head = temp;
   delete temp;

   tempTwo = new NodeType;
   (*tempTwo).data = 12;
   (*tempTwo).next = NULL;
   head -> next -> next = tempTwo;
   delete tempTwo;






}
4
remember: access a memory that has been free causes Undefined behavior at run time - Grijesh Chauhan

4 Answers

4
votes
delete temp;
delete tempTwo;

Remove these lines. You are deleting the memory you allocate, so that the next time you access it through head you get segfault.

You need to delete the blocks of memory you allocate, and this should happen after you are done using the memory. You don't need to delete every variable that touches that memory.

In your case, you can make a loop at the end of the main function which deletes the elements one by one (you need to save the next pointer first)

1
votes

When you do this

head = temp; // head and temp point to same object
delete temp; // object temp points to is de-allocated

you delete the object that temp points to, which is the same object that head points to. Then you de-reference head here:

head -> next -> next = tempTwo;

But head doesn't point to anything valid. De-referencing it is undefined behaviour.

1
votes

In the code

 temp = new NodeType;
   (*temp).data = 8;
   (*temp).next = head;
   head = temp;
   delete temp;

what is assigned to head is deleted. so here head point to garbage.So the line head -> next -> next = tempTwo; gives you segmentation fault. You are assigning to an invalid location.

0
votes
   head = temp;
   delete temp;

-- you delete the pointer and deference it later on

   head -> next -> next = tempTwo;