Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault implementing linkedlist

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.

like image 231
Richa Sachdev Avatar asked Jun 07 '26 08:06

Richa Sachdev


1 Answers

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);
like image 56
Swiss Avatar answered Jun 10 '26 02:06

Swiss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!