Segmentation Fault

My program compiles successfully although if I set one object equal to another, "segmentation fault" will appear in the output during runtime. Since thats the only time I get the message it led me to believe it was the copy constructor. Any help?

Here's the copy constructor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

template <typename T>
List<T>::List(const List<T> &aList)
	: size(aList.size)
{
	if(aList.head == NULL)
		head = NULL;	// original list is empty
		
	else
	{ // copy first node
		head = new ListNode<T>;
		head->item = aList.head->item;
		
		//copy rest of list
		ListNode<T> *newPtr = head;	// new list pointer
		// newPtr poinits to last node in new list
		// origPtr points to nodes in original list
		for (ListNode<T> *origPtr = aList.head->next;
			origPtr != NULL;
			origPtr = origPtr->next)
		{
			newPtr = newPtr->next;
			newPtr->item = origPtr->item;
		} //end for
		
		newPtr->next = NULL;
	} // end if
} // end copy constructor
This part is wrong. You're not allocating any new memory for the new elements!

1
2
			newPtr = newPtr->next;
			newPtr->item = origPtr->item;


Do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
		head = new ListNode<T>;
		head->item = aList.head->item;
		head->next = 0;      // YOU MUST INIT NEXT TO ZERO HERE.
		
		//copy rest of list
		ListNode<T> *newPtr = head;	// new list pointer
		// newPtr poinits to last node in new list
		// origPtr points to nodes in original list
		for (ListNode<T> *origPtr = aList.head->next;
			origPtr != NULL;
			origPtr = origPtr->next)
		{
			newPtr->next = new ListNode<T>;  // NEW NODE
			newPtr = newPtr->next;
			newPtr->item = origPtr->item;
			newPtr->next = 0;
		} //end for  // THESE KINDS OF COMMENTS ARE USUALLY USELESS 

Last edited on
Thanks a lot Hammurabi!

No more Segmentation Fault and I can't believe I missed that >.< !
Topic archived. No new replies allowed.