Question

Tried doing a simple linked list program , getting segmentation fault(core dumped) error, could anybody help on this. Not able to understand where exactly the pointers are messed up.

And can u suggest any other effective ways to write this

#include<iostream>
using namespace std;

struct node{
    int x;
    node *next;
}*head=NULL,*temp=head;


class list{
public:
    list(){
            temp=head;
    }
 //is something happening here causing core dump?
    void addnode(int value){
            if (head==NULL)
            {
                    head->x=value;
                    head->next=NULL;
            }
            else
            {
                    while(temp->next!=NULL)
                    temp=temp->next;
                    temp->next=new node;
                    temp=temp->next;
                    temp->x=value;
                    temp->next=NULL;
            }
    }

    void print(){
            while (temp->next!=NULL)
            {
                    cout<<temp->x<<" ";
                    temp=temp->next;
            }
    }
};

int main()
{
list l=list();
l.addnode(12);
l.addnode(23);
l.print();
return 0;
}
Was it helpful?

Solution

you forget to allocate object

void addnode(int value){
        if (head==NULL) 
        {
                head = new node; //here was a mistake
                head->x=value;
                head->next=NULL;

also delete global temp variable and use local

else
{
    node *temp = head;
    while(temp->next!=NULL)
        temp=temp->next;

}

void print(){
        node *temp = head;
        while (temp!=NULL) // here mistake too
        {
                cout<<temp->x<<" ";
                temp=temp->next;
        }
}

OTHER TIPS

You specifically test that head is NULL and, if so, you derefence head. That is clearly wrong. You probably wanted to first allocate a new node.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top