3

I have the following simple code but it is throwing segmentation fault. Can someone point what I am doing wrong? The segmentation fault comes after I input the first number.

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

    struct linked_list {
        int val;
        struct linked_list *next;
    } *curr, *head;


    typedef struct linked_list list;

    void createLinkedList(int num);
    void main() {
        int i;

        head = NULL;
        int num = 0;
        for (i = 0; i < 10; i++) {
            printf("Enter a number:");
            scanf("%d", num);
            createLinkedList(num);
        }
        curr = head;

        while(curr) {
            printf("%d\n", curr->val);
            head = curr->next;
        }

    }

    void createLinkedList(int n) {

          curr = (list *)malloc(sizeof(list));
          curr->val = n;
          curr->next = head;
          head = curr;
    }

Thanks.

gereeter
  • 4,731
  • 1
  • 28
  • 28
Richa Sachdev
  • 2,937
  • 3
  • 17
  • 12

1 Answers1

4

You are reading to num incorrectly. scanf takes a pointer to a integer, so it is trying to assign to memory location 0, which is invalid. Use & to reference the memory location of num.

Here is a corrected version:

scanf("%d", &num);
Swiss
  • 5,556
  • 1
  • 28
  • 42