Search code examples
c++c++98

Code runs perfectly but ends with a segmentation fault after running


I've determined that my remove function for removing nodes from a linked list is the problem, but I cant see why.

void LinkedList::remove(string license){
  moveToHead();
  while(currentPtr != NULL){
    if(getCurrent().get_licence() == license){
      if(currentPtr == headPtr){
        removeFromHead();
      }else if(currentPtr == tailPtr){
        removeFromTail();
      }else{
        currentPtr->getNext()->setPrev(currentPtr->getPrev());
        currentPtr->getPrev()->setNext(currentPtr->getNext());
        delete currentPtr;
        currentPtr = headPtr;
      }
    }
    forward();
    listLength--;
  }
  moveToHead();
}

moveToHead() moves my current pointer to head and forward() moves it to the next item on the list.

The code runs without issue, but I get a segmentation fault (core dumped) after it finishes running, rather than crashing when remove() is used


Solution

  • Just looking at the logic, you are calling forward(); and listLength--; even if if(getCurrent().get_licence() == license){ is true? Shouldn't you return if the correct license is found and removed?