minh anh b
minh anh b

Reputation: 51

How to resolve segmentation fault singly linked list?

Edit: Just tried doing while (temp != NULL && newNode->info > temp->info){ and it still doesn't work for some reason, I tried inputting 5 and 4 and got a segmentation error again

Sorry for the bad code I'm kind of new to this, I'm trying to make a sorted singly linked list. I'm not sure what's wrong with it and would greatly appreciate if somebody could help me with this issue?

I was able to perhaps input a couple values, each time a different number of values for some reason (not because I inputted -1). And then it just says "Exception has occurred. Segmentation error." on this particular line, and I'm not sure why since I was careful to compare values instead of the memory address:

while (newNode->info > temp->info){

Full code:

#include <iostream>
using namespace std;

class node {
public:
    int info;
    node *next;

    node (int data, node *ptr = 0) {
        info = data;
        next = ptr;
    }
};

class osll{

    public:
    node *head, *tail;

    osll(){
        head = tail = 0;
    }

    bool isEmpty(){
        return head == 0;
    }

    void sort(int input){

        node *newNode = new node (input);

        if (isEmpty()){
            newNode ->next = head;
            head = newNode;
            if (tail == 0)
                tail = head;
        }
        if (newNode ->info > head ->info){

            node *temp = head;
            while (newNode->info > temp->info){
                temp = temp ->next;
            }
            
            // will figure out how to link newNode to 
            // whatever temp value that stops here
            // once this error goes away
        }
    }

    
};



int main () {
    osll l;
    int input = 0;

    while (input != -1) {
        cout << "Enter a value: ";
        cin >> input;
        l.sort(input);
    }

    return 0;

}

Upvotes: 0

Views: 401

Answers (1)

Botond Horv&#225;th
Botond Horv&#225;th

Reputation: 1017

If your new number is the largest in the list it causes a segmentation-fault because you don't check if you reached the end of the list in the while-loop. After the last element temp will be null, so .temp->info will cause a segmentation-fault.

So you should do for example (line 40)

while (temp != null && newNode->info > temp->info)

Upvotes: 1

Related Questions