Friday, 16 August 2013

Seg fault in copy constructor doubly linked list

Seg fault in copy constructor doubly linked list

So, when I try to set the data of newPtr equal to the data of origPtr, I
receive a seg fault within the first lopp of the for-control-structure.
I'm not sure what is causing it. Is this maybe a misuse of my pointers? Or
a typo? Or perhaps a range error in my for loop's idiom?
List::List(const List &aList): numNodes(aList.numNodes) {
empty = true;
forward = true;
string flag;
cout << "Copy from head to tail? (y/n): ";
cin >> flag;
if(flag=="n")
forward = false;
if(!aList.head) {
head = NULL; //aList is empty. so is this->List.
tail = NULL;
} else { // copy 1st Node.
head = new Node;
if(forward)
head->setData(aList.head->getData());
else // copy in reverse.
head->setData(aList.tail->getData());
//copy rest of List.
Node *newPtr = head; //newPtr points to last Node in new List.
//origPtr points to nodes in original List.
if(forward) {
cout << "Copying normally...\n" << endl;
for(Node *origPtr=aList.head->getNext(); origPtr!=NULL;
origPtr=origPtr->getNext()) {
newPtr = newPtr->getNext();
newPtr->setData(origPtr->getData()); //SEG FAULT
} // end for
cout << "3" << endl;
} else {
cout << "Copying in reverse order...\n" << endl;
for(Node *origPtr=aList.tail->getPrev(); origPtr!=NULL;
origPtr=origPtr->getPrev()) {
newPtr = newPtr->getNext();
newPtr->setData(origPtr->getData()); //SEG FAULT
} // end for
} // end if/else
newPtr->setNext(NULL);
} // end if/else
cout << "Done copying!\n" << endl;
} // end copy constructor
If more code is necessary, I will make the necessary edits.
Also, I am aware that the standard for c++11 is to use nullptr. I will not
be using it for this implementation. I'm running on Ubuntu 12.04 with
gcc-v4.6.3, which does not support c++11.

No comments:

Post a Comment