Segmentation fault while implementing linked lists in C


(Vartiks) #1

i am getting a segmentation fault error while running the following code to implement linked list and the display them. your help would be appreciated.

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

typedef struct sl
{
    int num;
    struct sl * next;
}node;

void ins(node *, int);
void printll(node *);

int main(void)
{
    node * start;
    start=NULL;
    int n;
    char ch;
    do
    {
        printf("enter an integer \n");
        scanf(" %i",&n);
        ins(start,n);
        printf("do you want to insert more elements \n");
        scanf(" %c",&ch);
    }while(ch=='y');

    //print the linked list

    printll(start);
}

void ins(node *start, int n)
{
    if(start==NULL)
    {
        start=malloc(sizeof(node));
        start->num=n;
        start->next=NULL;
    }

    else
    {
        node * np;
        np=malloc(sizeof(node));
        np->num=n;
        np->next=start;
        start=np;
    }

}

void printll(node * start)
{
    node * nt=NULL;
    nt=start;
    printf("[[");
    while(nt->next!=NULL)
    {
        printf("%i>>",nt->num);
        nt=nt->next;
    }
    printf("]]");
}