Skip to content

Code runs perfectly but ends with a segmentation fault after running

An answer to this question on Stack Overflow.

Question

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

Answer

Use

g++ -fsanitize=address main.cpp

or a related variant to compile your code and then run it. This will tell you how you've misused memory to cause the segfault.