2

I'm stuck on printing this linked list without getting a segmentation fault. I think it is accessing something its not when its printing but Im not sure. I cant really tell whats wrong but I know its something really simple. P.S I want to keep the pointers to the head node and tail node.


#include <stdio.h>
#include <stdlib.h>

typedef struct node{
    
    int data;
    struct node* next;
}node;


node* addNode (node *head, node *tail, int val){
   
    node *newNode = (node) malloc(sizeof(node));
    newNode->data = val;


    if(head == NULL){
        head = newNode;
        tail = newNode;

    }
    else{

        tail->next = newNode;
        tail = newNode;

    }

    newNode->next = NULL;

    return newNode;



}

void printList(node *head){
    node *temp = head;

    while(temp->next != NULL){
        printf("%d\n", temp->data);
        temp = temp->next;
    }

}



int main()
{
    
    node* head = NULL;
    node* tail = NULL;
    node* tmp;
    
    for(int i = 0; i < 15; i++){
        tmp = addNode(head, tail, i*i);
    }


    printList(head);




    return 0;
}


Abdi Wali
  • 49
  • 5
  • 2
    Where does it get a segfault? – Neil Nov 13 '21 at 06:07
  • 1
    Following up on what @Neil asked, have you run it through valgrind? – Daniel Walker Nov 13 '21 at 06:13
  • 1
    Function args are passed by value in C. That means `head` and `tail` are local variables in the `addNode` function. Setting them does not change the caller's variables. That actual segfault is probably in `printList` as it does not correctly check for NULL head. Do basic debugging. Run your program and examine the variable values as it runs. – kaylum Nov 13 '21 at 06:14
  • 1
    Yea the seg fault is most likely in printList since the addNode function was working just fine. Ill run it through valgrind but I havent used it before so I'll see how it goes. – Abdi Wali Nov 13 '21 at 08:59

0 Answers0