简体   繁体   中英

initialize a linked list with a double pointer head node c++

I am not too sure why this code does not create a linked list with 5 nodes that each hold an integer value. I am currently getting a segfault and I commented on the line where the error is occurring. Any help would be appreciated, thank you.

struct node{
    int val;
    node * next;
}

int main(){
    node ** head;

    for(int i = 0; i < 5; i++){
        node * temp = new node;
        temp->val = i;

        (*head)->next = temp; //segfault here
    }
}

head doesn't need to be a pointer to a pointer. It can simply be a pointer to another node which is always the first node in your linked list. head should also be initialized to null .

In your code, head is a double pointer. The pointer that head is pointing to does not have a constructed object and may be null , hence your segmentation fault.

I would recommend you keep head a simple pointer instead of a double pointer as well, since that is unnecessary.

Try this one, it should work. You still have to write code to de allocate memory.

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

int main(){
   node * head = new node();
   head->val = 999;
   node *curr=head;

   for(int i = 0; i < 5; i++) {
      node* temp = new node();
      temp->val = i;
      cout << "adding node " << i << endl;
      curr->next = temp; //segfault here
      curr = curr->next;
   }
   return 0;
}

The first thing you try to do in your program using "node **head" is dereference it, which, given that head is a pointer of uninitialized value, will most likely crash your program if you try to touch any data at that location. The proper thing to do would be to set *head = temp before trying to go to next.

Additionally, you do not need to initialize the list using a double pointer to take advantage of the double pointer insertion algorithm later. You can always say Node **head_pp = &head and go from there.

Right now, your code looks like this.

Node **head (stores anything since uninitialized)

*head
(uninitialized memory)

(*head)->next (tries to touch uninitialized memory address, OS kills program)

It should be noted that in most cases you will receive the segfault error, since most uninit memory holds 0's. Eventually you would see an access violation, though

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