Seg faulting when printing Linked List in C

Viewed 31

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;
}


0 Answers
Related