简体   繁体   中英

Segmentation fault when creating linked list with function

I am trying to create a linked list and then echo the node values to the console. But using a function outside the main function and calling it is causing segmentation fault(core dumped) . I can't figure it out why. The following code works :

#include<iostream>
using std::cout;
using std::endl;

struct node
{
    int val;
    node* next;
};

void printList(node* start)
{
    node* temp; 
    temp = start;
    int i = 0;
    while(temp->next != NULL)
    {
        cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
        temp = temp->next;
        i++;
    }
}
int main() 
{
    node* start;
    node* temp;
    start = new node;
    temp = start;
    for(int i = 0; i < 10; i++)
    {
        temp->val = i*10;
        temp->next = new node;
        temp = temp->next;
    }
    temp->val = 0;
    temp->next = NULL;
    printList(start);
    return 0;
}

But this throws a segmentation fault

#include<iostream>
using std::cout;
using std::endl;

struct node
{
    int val;
    node* next;
};
void createList(node* start)
{
    node* temp;
    start = new node;
    temp = start;
    for(int i = 0; i < 10; i++)
    {
        temp->val = i*10;
        temp->next = new node;
        temp = temp->next;
    }
    temp->val = 0;
    temp->next = NULL;
}
void printList(node* start)
{
    node* temp; 
    temp = start;
    int i = 0;
    while(temp->next != NULL)
    {
        cout<<"The value in the "<<i<<"th node is : "<<temp->val<<endl;
        temp = temp->next;
        i++;
    }
}
int main() 
{
    node* start;
    createList(start);
    printList(start);
    return 0;
}

Change void createList(node* start) to void createList(node*& start) . ( See it work ).

In C++, unless specified otherwise, everything is passed by value. In this case, you're passing a pointer to a node ( start ) to createList by value . You can alter the node it points to ( start->... ), but not the pointer itself, as you're working with a copy.

Passing the pointer by reference allows you to change the pointer itself.

You're passing the start parameter into the function createList by value, which means that when you do

start = new node;

the copy of start is being assigned the address of the new node. This means that the start variable that you declare in main does not receive the address of the node.

To fix this, use a pointer reference. Pass start to createList by reference, instead of by value. Like this:

void createList(node*& start)

When you pass-by-reference, you're changing the pointer you declared in main directly, rather than creating a copy.

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