سؤال

I have determined that the error occurs when i call toString() method for my LinkedList class, more specifically when lines 8 or 9 are executed

string LinkedList::toString() const
{
    int traverse=1;
    Node * that = head;
    string sout;

    while(size>=traverse)
    {
        sout += "value = "+that->s +" ";
        that = that->next;
        traverse++;

    }
    return sout;

}

this LinkedList uses a Node class to store data that looks like this, and the LinkedList class itself has a int size variable and a pointer to the first Node

class Node
{
friend class LinkedList;
private:
    std::string s;
    Node * next;
    Node(std::string st, Node *nextn);
};

i'm guessing this is some dumb noob mistake on my part but i can't figure it out by staring at it or re-reading the tutorial on pointers

هل كانت مفيدة؟

المحلول

Without looking full code we can not guess where could be error. For current code it seems below code is faulty. Please add a log for null check

    that = that->next
    if(that ==null)

   {
       // std::cout<<"A null node found\n";
       break;
   }

نصائح أخرى

yes base issue is node *that is NULL at some point. 1) Seg Fault at First time access at first iteration in the loop .Cause: head from whihc it is copied is null .Chcek for the list pointer passed to this method is correct. 2) Segafult after few iterations in the loop. Cause: The traversal condition is not correct and goes beyond the list last node thereby trying to access NULL.

In either case you can try adding some cout statements within the loop and also adding check for "that" pointer.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top