0

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

asked Sep 13, 2021 at 15:37
6
  • 2
    Think for a while what traverser is when the loop ends. What condition must be met for the loop to end? Commented Sep 13, 2021 at 15:39
  • Ugrh... I was doing right ._. Why I change that line ._. Commented Sep 13, 2021 at 15:44
  • Aesthetic note: your while loop could easily be a for loop. E.g. for (traverser = &(this->head); traverser != nullptr; traverser = traverser->next); Commented Sep 13, 2021 at 16:04
  • @Chris Wow! OwO Commented Sep 13, 2021 at 16:05
  • Why do you have a head node instead of a pointer to the first node? There is no need for a head node. Commented Sep 13, 2021 at 17:09

1 Answer 1

1

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.

answered Sep 13, 2021 at 15:42

1 Comment

I forget to remove when edit code to post. But thanks anyway

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.