c program list accessing value segmentation fault

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

typedef struct node_struct {
    int data;
    struct node_struct *next;
} node;

typedef node *list;


int main()
{
    int temp;
    list head , tempList;
    char cont = 'Y';
    head = NULL;

    do {
        printf("Enter Data\n");
        scanf("%d",&temp); fflush(stdin);
        tempList = (list)malloc(sizeof(node));
        tempList->data = temp;
        tempList->next = head->next; // This line has error
        head->next = tempList;
        printf("Do you wish to continue (Y/N)\n");
        scanf("%c", &cont); fflush(stdin);
    } while (cont == 'Y');

    return 0;
}

Program received signal SIGSEGV, Segmentation fault. 0x08048516 in main () at listself.c:24

I want to point head pointer to the latest input value . but head->next gives me segmentation fault .

My question is how I can implement this logic ?

user input 1 : 5
user input 2 : 6
user input 3 : 3

and the internal structure of list be like

head -> 3 -> 6 -> 5

Also the while loop just exits before taking in the value for cont . propably it takes in "\n" . Any solution for that ?

Answers


Head is only a pointer and is not pointing to any memory so you cannot dereference it.

First you have to set the ->next value of tempList to NULL.

tempList->next = NULL ;

Then you have to change the way you use head.

tempList->next = head; // point it to NULL or the head
head = tempList;  // tempList becomes the new head

You need to allocate head before you refer to it.

Also, you need to set head->next to a value before you set tempList->next to head->next.

So...

head = (list)malloc(sizeof(node));
tempList = (list)malloc(sizeof(node));
head->next = NULL;
head->next = tempList;
tempList->data = temp;

Need Your Help

How can I assign event handler to event known from EventInfo?

c# .net vb.net winforms events

I would like to iterate over all events which a control (e.g. TextBox) supports and programmatically assign the same diagnostic event handler to each.

Parsing text using Regex

java regex

So I am trying to parse a String that contains two key components. One tells me the timing options, and the other is position.