0

I've read alot of the provided linked list segmentation faults on this site and attempted fixes like checking nullptrs before each use but I still can't get this to work. This is the link to the program on replit.

The program gives the intended result on test cases (using both input and command) 21 & 22 but gives segmentation faults on 23. Through method of elimination, I believe it is both the addNode & deleteByPhrase functions. The addNode function is supposed to insert a node at a given position within the linked list, and the deleteByPhrase function is supposed to delete any node whose phrase string contains the deletionPhrase.

void addNode(node* &h, int pos, string phrase)
{
    if(pos == 0)
    {
      h = new node;
      h->phrase = phrase;
      h->id = pos;
      nodeCount++;
      h->next = nullptr;
    }
    else if(pos <= nodeCount)
    {
      node* y;
      node* g;
      g = h;
      int count = 0;
      while(count != pos && g!=nullptr)
      {
        y = g;
        g = g->next;
        count++;
      }
      node *n;
      n = new node;
      n->id = pos;
      nodeCount++;
      n->phrase = phrase;
      n->next = g;
      y->next = n;
    }   
}

void deleteByPhrase(node* &h, string deletionPhrase)
{
   struct node* current = h;
   struct node* previous = nullptr;
      while(current != nullptr)
      {
        if(current->phrase.find(deletionPhrase) != string::npos)
        {
          if(current == h) {
          h = h->next;
          }else{
          previous->next = nullptr;}
          nodeCount--;
        }
         //store reference to current link
         previous = current;
         current = current->next;
      }
}
  • 2
    [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). Much faster than debugging via StackOverflow. – Eljay Sep 20 '21 at 23:03
  • 1
    Are you required to have a `pos`? If so, think over the logic for `pos == 0` because it looks a lot like it will nuke the linked list if the list is not empty. – user4581301 Sep 20 '21 at 23:16
  • See the *Community Addition* to [this answer](https://stackoverflow.com/a/22122095/4581301) for one of the better ways to find and eliminate an unwanted node. You can use the same trick to simplify insertion. – user4581301 Sep 20 '21 at 23:18
  • My alternative would be to write an actual linked list *class* instead of a C-style linked list in C++. – sweenish Sep 21 '21 at 02:41

0 Answers0