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 ?


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.


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

Need Your Help

Registering a user?

android libgdx kryonet

I need to create a login/register system for my game but I have no clue on how this is commonly done. I already have setup a working client/server system with Kryonet where I can push data over the

Return next customer visit date

ms-access ms-access-2007

I have a table with unique customers in with their last visit date. I have another historical table that contains all of their visits plus any future dates booked in. I need to be able to return th...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.