0

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;






}
1
  • remember: access a memory that has been free causes Undefined behavior at run time Commented Jul 2, 2013 at 6:07

4 Answers 4

3
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)

Sign up to request clarification or add additional context in comments.

2 Comments

Ideally, wouldn't that statement come in the destructor? Without the delete statement, the memory isn't being returned to the system when the object goes out of scope.
@RichardD he could make a recursive destructor in his Node class, but it is probably preferable to do it iteratively at the end of the main function as I advice.
1

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.

Comments

1

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.

Comments

0
   head = temp;
   delete temp;

-- you delete the pointer and deference it later on

   head -> next -> next = tempTwo;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.