Home > Blockchain >  Insert node of linked list at the end but program keep crashing
Insert node of linked list at the end but program keep crashing

Time:09-17

As the title say, I tried to insert node of linked list at the end but C program keep crashing

class SymbolTable
{
  struct Node
  {
    string id;
    int num;
    string str;
    Node *next;
  };

public:
  SymbolTable() {}
  void insert(string id);

private:
  Node head = { "head", -99, "", nullptr};
};



void SymbolTable::insert(string id)
{
  Node *traverser = &(this->head);
  while (traverser != nullptr) { traverser = traverser->next; }

  Node *newNode = new Node();
  newNode->id = id;
  newNode->next = nullptr;
  traverser->next = newNode; // --> Crashing
}

I don't see any problem.

Answer:

traverser != nullptr should be traverser->next != nullptr

CodePudding user response:

I do find few problems, first of all in-class definition you declared function insert as:

void insert(string id, string type);

however, when you declare a function outside of it you skipped 2nd argument:

void SymbolTable::insert(string id);

I don't understand how this code would even compile. I also fixed algorithm itself:

void SymbolTable::insert(string id)
{
    Node* traverser = &(this->head);
    while (traverser->next != nullptr) //used to be (traverse !=nullptr)
    { 
      traverser = traverser->next;
    }

    Node* newNode = new Node();
    newNode->id = id;
    newNode->next = nullptr;
    traverser->next = newNode; 
}

Issue was that you were checking if traverse is null, not if the next of traverser is null. In consequence, you were referring to traverser which was a nullpointer. After this little fix code compiles just fine after inserting.

  • Related