-3

I am creating a simple linked list program to insert and view the elements of LL. When I try to insert second element it gives SIGSEV, but I cannot understand why??!!

Please help me point the issue:

main.c:

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

typedef struct linkedList{
    int data;
    struct linkedList *next;
}LL;

LL *start;

int main(){

    int option = 0;
    while(1){
    printf("Enter option: \n");
    scanf("%d", &option);

    switch(option){
       case 1:
         addNode(start);
         break;
       case 2:
         readNodes(start);
         break;
       case 3:
         exit(0);
    }
    }
}

insert Node:

int addNode(LL *startNode){

    LL *temp, *node;
    int data = 0;

    printf("Enter data: ");
    scanf("%d", &data);

    if(startNode == NULL){/*Application only when the first element is inserted*/
        startNode = (LL*)malloc(sizeof(LL*));
        if(startNode == NULL){
          printf("Error: Memory not allocated!!\n");
          exit(1);
        }
        startNode->data = data;
        startNode->next = NULL;
        start = startNode;

        return 0;
    }

    temp = startNode;

    while(temp != NULL){
        temp = temp->next;
    }

    node = (LL*)malloc(sizeof(LL*));
    node->data = data;
    node->next = NULL;

    temp->next = node;

    temp = temp->next;

    return 0;
}
Amrit
  • 2,295
  • 4
  • 25
  • 42

1 Answers1

2
  1. sizeof takes length of structure , you always pass 4 bytes in your case for 32 bit architecture
  2. your while loop for iterating temp node is wrong , you should rather check for next node to be NULL.
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
Bankelaal
  • 408
  • 1
  • 9
  • 24