I'm trying to traverse to the end of a linked list, but I get a segmentation fault when my while loop checks to see if the "next" pointer is null. Any suggestions on how to perform this check without causing a segmentation fault would be greatly appreciated.

Recommended Answers

All 3 Replies

It's legal to compare any pointer value with null pointer or any others pointer values of the same type.
Better post your code fragment with segmentation fault. It's annoying to download the whole source, didn't you understand it?

commented: Good clarification! +7

Sorry for the annoyance. I posted everything because I wasn't sure that a code fragment would be understandable due to the number of classes functions that I wrote myself.

Vertex ** al;  // declare the adjacency list
al = new Vertex * [numLocations];

ListNode * current; // pointer to current list node
current = al[begin]->returnFirstListNode();

// while the current ListNode's next pointer is not NULL, advance to the next ListNode 
while(current->returnNext() != NULL) // comparison causes segmentation fault
{
   // skip to the next node
   current = current->returnNext();
}

// in the ListNode class:

ListNode * ListNode::returnNext()
{
  ListNode * nextCopy;
  nextCopy = ListNode::next; // ListNode::next is a pointer to the next ListNode in the list
  return nextCopy;
}

There are lots of possible causes, for example:
- value of begin index is out of range
- current == 0 before while loop for empty list
- memory corruption
...
The last point: Vertex::changeName is wrong:

int Vertex::changeName(char * inputname) // const char* !
{
  int length; // better size_t or unsigned type
  length = strlen(inputname); // forgot to count zero byte
  Vertex::name = (char *) malloc (length); // no room for zero byte
  strcpy(Vertex::name, inputname); // 100% memory corruption
  return 0; // why? better void changeName
}

Stop using dynamically allocated C-strings! You will never debug this code with awkward and error-prone sequences of malloc/new-strcpy. Use std::string for string data.

Stop using mix of malloc/new! Use new/delete only in C++ programs! Don't use non-standard strdup function!

It's impossible to run your code (no external files). Next time make zipped attachment (a single compact file) to your posts.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.