-5
#include<iostream>

using namespace std;

class Node{
    public:
    int data;
    Node* next;
};

class LinkedLIst{
    private:
    Node* head;
    public:
    
    LinkedLIst(){
        head=NULL;
    }
    
    void addNode(int data){
        Node* newNode = new Node();
        newNode->data = data;
        newNode->next = NULL;
        
        if(head == NULL){
            head = newNode;
        }
        else{
            Node* temp = head;
            while(temp!=NULL){
                temp = temp->next;
            }
            temp->next = newNode;// I think fault is here.
        }
    }
    
    void display(){
        Node* temp = head;
            while(temp!=NULL){
                cout<<temp->data<<" ";
                temp = temp->next;
            }
    }
    
    
    
};

int main(){
    
    LinkedLIst* lt = new LinkedLIst();
    lt->addNode(100);
    lt->addNode(200);
    lt->addNode(300);
    lt->display();
    return 0;
}

I am getting Segmentation fault(core dumbed) when i am running this code

drescherjm
  • 10,365
  • 5
  • 44
  • 64

1 Answers1

1
Node* temp = head;
while(temp!=NULL){
    temp = temp->next;
}

This will guarantee that the only way you get out of this loop is if temp is null. And what do you do on the next line?

temp->next = newNode;// I think fault is here.

Dereference temp! You probably wanted temp to point to the last node after the loop. You could do that with:

Node* temp = head;
while(temp!=NULL && temp->next != NULL){
    temp = temp->next;
}

Or even cleaner (imo) since you've already checked head to be null in the if branch above this, we don't need to check temp != NULL and we can condense it all into a for loop:

for(Note *temp = head; temp->next != NULL; temp = temp->next) { }
scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Not at all convinced by the "even cleaner" version that's ten times harder to read and understand, but hey ;) – Asteroids With Wings Sep 21 '20 at 14:37
  • @Asteroids I've added that missing line in for the `while` examples to (hopefully) make things less confusing and killed a useless condition in the for to make it a little cleaner. But I stand behind the weak defense that "(imo)" gives me to say that being cleaner is your choice :) – scohe001 Sep 21 '20 at 14:41