Linked list Runtime error...

This is a discussion on Linked list Runtime error... within the C++ Programming forums, part of the General Programming Boards category; When i run my program and add a few nodes to my linked list and then when i try to ...

  1. #1
    Registered User
    Join Date
    Jul 2012
    Posts
    36

    Question Linked list Runtime error...

    When i run my program and add a few nodes to my linked list and then when i try to delete nodes a runtime error occurs that states: Program received signal SIGSEGV, Segmentation fault.

    here's the program: can anyone help please???
    Code:
    #include <iostream>
    using namespace std;
    
    
    struct node{
    
    
        int a;
        int id;
        node *next;
    
    
    };
    
    
    
    
    node *X,*Y,*Z,*U;
    
    
    node *createNode(int num,int i);
    void addToList(node* z);
    void display();
    void deleteNode(int ID);
    
    
    int main(){
    
    
        char d;
        do{
            char c;
            cout << "Choose:\n1)Create node\n2)Delete node\n3)Display list\n4)Exit\n\nWrite 1,2 or 3: ";
            int uva;
            cin >> uva;
            cin.ignore();
            if(uva == 1){
                do{
    
    
                    cout << "Enter a number: ";
                    int a;
                    cin >> a;
                    cin.ignore();
                    cout << "Enter an id for your node: ";
                    int i;
                    cin >> i;
                    Z = createNode(a,i);
                    addToList(Z);
                    cout << "Do you want to create an new node?(y/n): ";
                    cin >> c;
                    cin.ignore();
    
    
                }while(c == 'y' ||  c == 'Y');
    
    
    
    
            }else if(uva == 2) {
    
    
                cout << "Enter the id of the node to delete: ";
                int uno;
                cin >> uno;
                deleteNode(uno);
    
    
            }else if(uva == 3){
    
    
                cout << "Do you want to display the whole list?(y/n): ";
                cin >> c;
                cin.ignore();
                if(c == 'y' || c == 'Y')
                display();
    
    
            }else if(uva == 4){
    
    
                cout << "\n\n===PRESS ENTER TO EXIT===";
        cin.get();
        return 0;
    
    
            }else{
    
    
                cout << "UNKNOW NUMBER!!";
    
    
            }
    
    
    
    
            cout << "\n\nDo you want to use the program again?(y/n): ";
            cin >> d;
            cin.ignore();
        }while(d == 'y' || d == 'Y');
    
    
    
    
        cout << "\n\n===PRESS ENTER TO EXIT===";
        cin.get();
    
    
    }
    
    
    node *createNode(int num,int i){
    
    
        node *oneobj = new node;
        oneobj -> a = num;
        oneobj->next = NULL;
        oneobj->id = i;
    
    
    
    
    
    
        return oneobj;
    
    
    }
    
    
    void addToList(node* z){
    
    
        if(X == NULL){
    
    
            X = Y =  z;
    
    
        }
        else{
    
    
            Y->next = z;
            Y=z;
    
    
        }
    
    
    }
    void display(){
    
    
        while(X->next != NULL){
    
    
            if(X != NULL){
    
    
    
    
                cout<< X->a << " -> ";
                X = X->next;
    
    
    
    
            }
    
    
        }
        cout << X->a << " -> NULL";
    
    
    }
    void deleteNode(int ID){
    
    
        while(X->id != ID){
    
    
            X = X->next;
    
    
        }
        U = X;
        X = X->next;
        delete U;
    
    
    }
    Last edited by tennisstar; 11-07-2012 at 08:21 AM.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    > while(X->next != NULL)
    1. It should be while ( X != NULL )
    2. You're trashing your single GLOBAL variable pointing to the list.

    Try passing some parameters to functions.
    Code:
    void display(node *list){
      while ( list != NULL ) {
        list = list->next;
      }
    }
    No messy globals, it can be used for any node* type list you happen to have, and nothing gets permanently changed.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    1. Variable names. X and Y (also U and Z) are awful names for variables. From context for example I can see that better names for X and Y would be "head" and "tail". And you should avoid globals as mentioned already.

    2. Uninitialized variables:
    Code:
    struct node{
    
        int a;
        int id;
        node *next;
     
    };
     
    
    node *X,*Y,*Z,*U;
    
    ...
    
    void addToList(node* z){
     
     
        if(X == NULL){
     
           X = Y =  z;
     
     
        }
        else{
     
     
            Y->next = z;
            Y=z;
     
     
        ...
    Where do you first initialize X (or Y) prior to testing whether it is NULL or not? Nowhere, X is uninitialized and probably not equal to NULL. Therefore you likely go down the "else" path and start attempting to dereference the uninitialized pointer Y. This would definitely cause a segfault.

    3. ???
    Code:
    void deleteNode(int ID){
     
     
        while(X->id != ID){
     
     
            X = X->next;
     
     
        }
        U = X;
        X = X->next;
        delete U;
     
     
    }
    First off, X = X->next destroys your ability to track the beginning of the list. Salem mentions this in his post as well. The rest of the code means that after deleting a node given a specific ID, your list will consist of a head pointer X pointing at the node after the deleted node. Nodes prior to the deleted node are lost/unreachable.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,535
    > Nowhere, X is uninitialized and probably not equal to NULL.
    Being global, it will be NULL.
    But that's about as far as the luck runs.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  5. #5
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Ah, forgot about that. Thanks.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  6. #6
    Registered User
    Join Date
    Jul 2012
    Posts
    36
    hello every one
    its me tennisstar...

    i tried to improve my code but the problem still exists
    i couldn't understand what you were saying...
    in the insertNode function if the variable is not NULL then the else block will run...
    so what is the mistake?
    kindly explain in simple terms...
    a humble request of a beginner...

    here's my improved version that doesn't destroy the variable that points to the starting of the list:

    Code:
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    
    struct node{
    
    
        int a;
        node *b;
    
    
    };
    
    
    node *e = NULL;
    node *g = NULL;
    node *h = NULL;
    node *i = NULL;
    
    
    node* createNode(int c){
    
    
        node *newNode = new node;
        newNode -> a = c;
        newNode -> b = NULL;
    
    
        return newNode;
    
    
    }
    
    
    void insertNode(node* d){
    
    
        if(e == NULL)
            e = h = d;
        else{
            h -> b = d;
            h = d;
        }
    
    
    }
    
    
    void display(){
    
    
        h = e;
        while(h != NULL){
            if(h -> b != NULL){
                cout << h -> a << " -> ";
            }else{
                cout << h -> a  << " -> NULL";
            }
    
    
            h = h -> b;
    
    
        }
    
    
    
    
    }
    
    
    void deleteNode(int f){
    
    
        g = e;
        while(g -> a != f)
            g = g -> b;
        i = g;
        g = g -> b;
        delete i;
    
    
    }
    
    
    int main(){
    
    
        char n = 'y';
        char o = 'y';
        do{
            system("cls");
            cout << "WELCOME TO THE LINKED LIST PROGRAM...\n===\n\nWhat do you want to do next? ";
            short j;
            cout << "\n1)Create node...\n2)Delete node...\n3)Display node...\n4)Exit...";
            cout << "\n===\n\nYour choice (1,2,3 or 4): ";
            cin >> j;
            cin.ignore();
            if(j == 1)  {
    
    
                    while(o == 'y' || o == 'Y'){
    
    
                        cout << "Enter a number to be stored in the node: ";
                        int k;
                        cin >> k;
                        cin.ignore();
                        node* l;
                        l = createNode(k);
                        insertNode(l);
                        cout << "Node created successfully...\nNode added to list successfully...\n\n===";
                        cout << "Do you want to add more nodes?(y/n): ";
                        cin >> o;
                        cin.ignore();
    
    
                    }
                    cout << "\nPRESS ENTER TO CONTINUE...";
                    cin.get();
                    o = 'y';
        }
                else if( j == 2){
                    cout << "Enter the number stored in the node to be deleted: ";
                    int m;
                    cin >> m;
                    deleteNode(m);
                    cout << "Node successfully deleted...\n\n===";
                    cout << "\nPRESS ENTER TO CONTINUE...";
                    cin.get();
                }
                else if( j == 3){
                    display();
                    cout << "\n\n===";
                    cout << "\nPRESS ENTER TO CONTINUE...";
                    cin.get();
                }
                else if( j == 4){
                    cout << "THANKYOU FOR USING THE PROGRAM!!!\n\n===PRESS ENTER TO EXIT===";
                    cin.get();
                    return 0;
                }
                else{
                    cout << "Unknown decision...\n\n===";
                    cout << "\nPRESS ENTER TO CONTINUE...";
                    cin.get();
                }
    
    
    
    
        }while(n == 'y');
    
    
    
    
    }
    please help in simple terms..
    thanx in advance...
    Last edited by tennisstar; 11-11-2012 at 07:35 AM.

  7. #7
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    You should use variable names that actually have a meaning. You had a "next" pointer in your first attempt. Why did you name that "b"? b is nothing. it has no meaning. It is hard to read. Every function you have, I would have to figure out by myself when you, who wrote it, already knew what it should do.

    Use descriptive variable names. Name your b pointer "next". One of your variables will be "head" and one will probably be "tail". Then it is way easier to spot mistakes.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  8. #8
    Registered User
    Join Date
    Jul 2012
    Posts
    36
    hey guys...
    you people told me to put nice names, so i did..
    you also told that a few vars. were uninitialized , so i initialized them...

    but i do get an error....
    (note: this is an entirely new program so kindly carefully go through it):

    Code:
    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    
    struct node{
    
    
        int data;
        node *link;
    
    
    };
    
    
    node *head = NULL;
    node *traverser = NULL;
    
    
    node* create(int data){
    
    
        node *tempNode = new node;
        tempNode -> data = data;
        tempNode -> link = NULL;
    
    
        return tempNode;
    
    
    }
    
    
    void insertFirst(node *nodeToBeInserted){
    
    
        head = traverser = nodeToBeInserted;
    
    
    }
    
    
    void insertCustom(int insertAfter,node* nodeToBeInserted){
    
    
        node *current = head;
        node *tempNode,*tempNode2;
        while(current != NULL){
    
    
            if(current -> data == insertAfter){
    
    
                tempNode2 = current -> link;
                current -> link = tempNode = new node;
                tempNode = nodeToBeInserted;
                tempNode -> link = tempNode2;
                break;
    
    
            }else{
    
    
                current = current -> link;
    
    
            }
    
    
        }
        if(current == NULL){
    
    
            cout << "Sorry user, the entire list was searched but a node with the value " << insertAfter << " was not found!!!" << endl;
    
    
        }
    
    
    }
    
    
    void deleteFirst(){
    
    
        node *tempVar = head;
        head = traverser = head -> link;
        delete tempVar;
    
    
    }
    
    
    void deleteCustom(int deletableNodesData){
    
    
        node *tempVar = head,*tempVar2;
        node *trail = NULL;
    
    
        while(tempVar != NULL){
    
    
            if(tempVar -> data == deletableNodesData){
    
    
                tempVar2 = tempVar;
                tempVar = tempVar -> link;
                delete tempVar2;
                trail = tempVar;
    
    
            }else{
    
    
                tempVar = tempVar -> link;
                trail = tempVar;
    
    
            }
    
    
        }
        if(tempVar == NULL){
    
    
            cout << "Sorry user, the entire list was searched but there wasn't any node that contained " << deletableNodesData << ")....";
    
    
        }
    
    
    }
    
    
    void display(){
    
    
        node *tempVar = head;
        while(tempVar != NULL){
    
    
            if(tempVar -> link != NULL){
    
    
                cout << tempVar -> data << " =>";
    
    
            }else{
    
    
                cout << tempVar -> data << " => NULL";
    
    
            }
            tempVar = tempVar -> link;
    
    
        }
    
    
    }
    
    
    
    
    int main(){
    
    
        char x = 'y';
        while(x == 'y' || x == 'Y'){
            cout << "Welcome to the linked list program...";
            cout << "Here's our menu:\n1)Create node...\n2)Delete node...\n3)Display node...\n4)Exit...";
            cout << "\n\nEnter choice (1,2,3 or 4): ";
            int a;
            cin >> a;
            cin.ignore();
            if(a == 1){
    
    
                cout << "Enter a number, to be stored in the node to be created: ";
                int b;
                cin >> b;
                cin.ignore();
                node *temp = create(b);
                if(head == NULL){
    
    
                    insertFirst(temp);
                    cout << "Successfully created and added the node...\n(The node was added in the beginning of the list since there wasn't any other node)...";
    
    
                }else{
    
    
                    cout << "After which node do you wanna insert this node?(Enter the data stored in that node): ";
                    int c;
                    cin >> c;
                    cin.ignore();
                    insertCustom(c,temp);
                    cout << "Successfully created and added the node...\n(After the node containing " << c << " in it)...";
    
    
                }
    
    
            }else if(a == 2){
    
    
                cout << "Enter the data stored in the node to be deleted: ";
                int d;
                cin >> d;
                cin.ignore();
                if(head -> data == d){
    
    
                    deleteFirst();
                    cout << "Successfully deleted the node containing " << d << " in it...";
    
    
                }else{
    
    
                    deleteCustom(d);
                    cout << "Successfully deleted the node containing " << d << " in it...";
    
    
                }
    
    
            }else if(a == 3){
    
    
                display();
    
    
            }else if(a == 4){
    
    
                cout << "===PRESS ENTER TO EXIT===";
                cin.get();
                return 0;
    
    
            }else{
    
    
                cout << "Sorry user the program doesn't recognise " << a << " as a command..\nPlease try again...";
    
    
            }
            cout << "Do you wanna use the program again?(y/n): ";
            cin >> x;
            system("cls");
    
    
        }
    
    
    }

  9. #9
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,304
    You know what else would make it easier to read? Not having large amounts of random whitespace everywhere. By all means use whitespace, but one blank line is enough, and only use it in places where emphasis is required.

    Gotta go, no more time left to look at this tonight.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  10. #10
    Registered User
    Join Date
    Jul 2012
    Posts
    36
    Hello everyone....
    it's me tennisstar...

    i programmed about 6 hours today and i finaly made a successful Linked list program and other than deletion and creation of
    nodes i added some more functionality to my program such as searching for nodes or calculating the size of the entire list...

    here's the code for my successful program, do try the code out:
    Code:
    #include<iostream>
    #include<cstdlib>
    using namespace std;
    
    
    struct node{
    
    
        int data;
        node* link;
    
    
    };
    
    
    node* head = NULL,*trav = NULL;
    
    
    node* createNode(int data){
    
    
        node* tempNode = new node;
        tempNode -> data = data;
        tempNode -> link = NULL;
    
    
        cout << "Successfully created node...";
    
    
        return tempNode;
    
    
    }
    
    
    void insertNode(node* nodeToBeInserted){
    
    
        if(head == NULL){
    
    
            head = trav = nodeToBeInserted;
            cout << "\nSuccessfully added node to list...";
    
    
        }else{
    
    
            trav -> link = nodeToBeInserted;
            trav = trav -> link;
            cout << "\nSuccessfully added node to list...";
    
    
        }
    
    
    }
    
    
    void deleteNode(int data){
    
    
        node* tempNode = head;
        node* trail = NULL;
        node* tempVar;
    
    
        if(head -> data == data){
    
    
            tempVar = head;
            head = head -> link;
            delete tempVar;
    
    
        }else{
    
    
            while(tempNode != NULL){
    
    
                if(tempNode -> data == data){
    
    
                    tempVar = tempNode;
                    tempNode = tempNode -> link;
                    delete tempVar;
                    trail -> link = tempNode;
                    break;
    
    
                }else{
    
    
                    trail = tempNode;
                    tempNode = tempNode -> link;
    
    
                }
    
    
            }
    
    
        }
        if(tempNode == NULL){
    
    
                cout << "Sorry user, the entire list was searched but no node to be deleted was found with " << data << " in it...";
    
    
            }else{
    
    
                cout << "Node successfully deleted...";
    
    
            }
    
    
    }
    
    
    void display(){
    
    
        node* tempVar = head;
        if(head == NULL){
    
    
            cout << "NULL => NULL";
    
    
        }
        while(tempVar != NULL){
    
    
            if(tempVar -> link != NULL){
    
    
                cout << tempVar -> data << " => ";
    
    
            }else{
    
    
                cout << tempVar -> data << " => NULL...";
    
    
            }
    
    
            tempVar = tempVar -> link;
    
    
        }
    
    
    }
    
    
    void calculateSize(){
    
    
        node* tempVar = head;
        int listSize = 0;
        while(tempVar != NULL){
    
    
            listSize++;
            tempVar = tempVar -> link;
    
    
        }
        cout << "The size of the LinkedList is " << listSize << " nodes...\ni.e. it is made up of " << listSize << " nodes...";
    
    
    }
    
    
    void searchList(int data){
    
    
        node* tempVar = head;
        int nodePos = 1;
        while(tempVar != NULL){
    
    
            if(tempVar -> data == data){
    
    
                cout << "The node was found at position " << nodePos << " in the list...";
                break;
    
    
            }
            nodePos++;
            tempVar = tempVar -> link;
    
    
        }
        if(tempVar == NULL){
    
    
            cout << "The entire list was searched but no node was found that contained " << data << " in it...";
    
    
        }
    
    
    }
    
    
    int main(){
    
    
        char x;
        do{
    
    
            cout << "WELCOME TO THE LINKED LIST PROGRAM...\n\nOur Menu:\n";
            cout << "1)Create node...\n2)Delete node...\n3)Display list...\n4)Caluclate list-size...\n5)Search list...\n6Exit...";
            int a;
            cout << "\n===\nEnter choice(1,2,3 or 4): ";
            cin >> a;
            cin.ignore();
            if(a == 1){
    
    
                cout << "\nEnter data to be stored in your brand new node here: ";
                int data;
                cin >> data;
                node* tempVar = createNode(data);
                insertNode(tempVar);
    
    
            }else if(a == 2){
    
    
                cout << "\nEnter data stored in the node which you wanna delete: ";
                int deletable_data;
                cin >> deletable_data;
                deleteNode(deletable_data);
    
    
            }else if(a == 3){
    
    
                display();
    
    
            }else if(a == 6){
    
    
                cout << "\n===PRESS ENTER TO EXIT===";
                cin.get();
                return 0;
    
    
            }else if(a == 4){
    
    
                calculateSize();
    
    
            }else if(a == 5){
    
    
                cout << "Enter data stored in the node to be searched: ";
                int data;
                cin >> data;
                searchList(data);
    
    
            }else{
    
    
                cout << "\nUnknown command...";
    
    
            }
            cout << "\n\nDo you wanna use the program again?(y/n): ";
            cin >> x;
            cin.ignore();
            system("cls");
    
    
        }while(x == 'y' || x == 'Y');
    
    
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linked List Error
    By eleceng16 in forum C Programming
    Replies: 7
    Last Post: 04-13-2012, 06:59 AM
  2. linked list error....
    By roaan in forum C Programming
    Replies: 6
    Last Post: 07-09-2009, 08:56 PM
  3. Runtime error using list<int>.erase()
    By cyanfish in forum C++ Programming
    Replies: 6
    Last Post: 11-18-2006, 12:09 PM
  4. Help with some error...(linked list)
    By google@ in forum C Programming
    Replies: 5
    Last Post: 11-08-2006, 07:29 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21