简体   繁体   中英

Inserting a single element in a linked list gives a segmentation fault - C++

The below code intends to perform insertion of a single element in a linked list and then print it. Although, I am getting a segmentation fault while printing the value in main function. Could you please help me identify what is wrong with it ?

I have tried to print the value of data in the insert function and it works fine which means the creation of new node and assignment of the value to it is working fine.

#include<iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

//insert a new node
Node* insertNode(int data,Node* head)
{
    Node* cNode = head;
   if (!head)
   {
       head = new Node;
       head->data = data;
       head->next = NULL;
   }
   else
   {
       while(cNode->next)
       {
           cNode = cNode->next;
       }
       cNode->next = new Node;
       cNode->next->data = data;
       cNode->next->next = NULL;
   }
   return head;
}

// print a list
void print(Node* head)
{
    /*while(head->next)
    {
        cout << head->data << " ";
        head = head->next;
    }*/
    cout << "printing data" << endl;
    cout << "data : " << head->data;
}
int main()
{
    cout << "inside main" << endl;
    Node* aNode = NULL;
    insertNode(2,aNode);
    print(aNode);
    return 0;
}

I expect the print function to print the value of data for the single node that I created .

Your head parameter in insertNode function should be a reference (or a pointer to pointer to Node). Beacause in the current form, it is an input parameter, but you need to be in-out parameter. It means that in the current code, your aNode variable is NULL and is always stays NULL.

I recommend this: void insertNode(int data, Node &head)

Then you create an object in main this way: Node aNode;

It will allow you to update the existing variable directly and you don't need a return value. Also, this way it will be a little bit more C++like, your original code is more like a plain C code.

Or if you want to write it in plain C: void insertNode(int data, Node **head)

Then you change the call from main : insertNode(2, &aNode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM