I’ve been unable to complete my homework because I cannot seem to identify the source of this segmentation fault.
I am trying to add nodes to a linked list from a file. I’ve run multiple tests and have narrowed the problem down quite a bit, but, I don’t know what’s actually creating the problem and therefore I create new problems when I try to change other details.
This is my second course, so, hopefully my code isn’t so bad that it can’t be helped.
Here’s the add method:
bool OrderedList::add (CustomerNode* newEntry)
{
if (newEntry != 0)
{
CustomerNode * current;
CustomerNode * previous = NULL;
if(!head)
head = newEntry;
current = head;
// initialize "current" & "previous" pointers for list traversal
while(current && *newEntry < *current) // location not yet found (use short-circuit evaluation)
{
// move on to next location to check
previous = current;
current = current->getNext();
}
// insert node at found location (2 cases: at head or not at head)
//if previous did not acquire a value, then the newEntry was
//superior to the first in the list.
if(previous = NULL)
head = newEntry;
else
{
previous->setNext(newEntry); //Previous now needs to point to the newEntry
newEntry->setNext(current); //and the newEntry points to the value stored in current.
}
}
return newEntry != 0; // success or failure
}
Okay, there is an overloaded operator< included in the program, outside testing does not indicate a problem with the operator, but I will include it as well:
bool CustomerNode::operator< (const CustomerNode& op2) const
{
bool result = true;
//Variable to carry & return result
//Initialize to true, and then:
if (strcmp(op2.lastName, lastName))
result = false;
return result;
}
And here is the backtrace from gdb:
#0 0x00401647 in CustomerNode::setNext(CustomerNode*) ()
#1 0x00401860 in OrderedList::add(CustomerNode*) ()
#2 0x004012b9 in _fu3___ZSt4cout ()
#3 0x61007535 in _cygwin_exit_return () from /usr/bin/cygwin1.dll
#4 0x00000001 in ?? ()
#5 0x800280e8 in ?? ()
#6 0x00000000 in ?? ()
This was the result of a lot of work of trying to correct a different segfault, and this one was much more surprising. I have no idea how my setNext method is causing a problem, here it is:
void CustomerNode::setNext (CustomerNode* newNext)
{
//set next to newNext being passed
next = newNext;
return;
}
Thanks in advance, I will be glad to post more of the code if it is necessary to identifying this problem.
It’s
instead of
This sets
previoustoNULLand then enters theelsebranch:resulting in undefined behavior.